Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a base class constructor from derived class in Java

Tags:

java

I have a class as follows:

public class Polygon  extends Shape{      private int noSides;     private int lenghts[];      public Polygon(int id,Point center,int noSides,int lengths[]) {         super(id, center);         this.noSides = noSides;         this.lenghts = lengths;     } } 

Now a regular polygon is a polygon whose all sides are equal. What should be the constructor of my regular polygon?

public Regularpolygon extends Polygon{  //constructor ??? } 
like image 951
akshay Avatar asked Aug 17 '10 17:08

akshay


People also ask

How do you call a base class constructor from a derived class constructor?

How to call the parameterized constructor of base class in derived class constructor? To call the parameterized constructor of base class when derived class's parameterized constructor is called, you have to explicitly specify the base class's parameterized constructor in derived class as shown in below program: C++

How do you call a base class constructor?

Example of Base Class Constructor Calling When we create the object of Pqr class then first it will call Pqr class constructor but Pqr class constructor first initialize the base class constructor then Pqr constructor will be initialized.

Is base class constructor called First Java?

The compiler knows that when an object of a child class is created, the base class constructor is called first. And if you try to manually change this behavior, the compiler won't allow it.

Which of this keyword must be used to call base class constructor?

Using the super Keyword to Call a Base Class Constructor in Java.


2 Answers

public class Polygon  extends Shape {         private int noSides;     private int lenghts[];      public Polygon(int id,Point center,int noSides,int lengths[]) {         super(id, center);         this.noSides = noSides;         this.lenghts = lengths;     } }  public class RegularPolygon extends Polygon {     private static int[] getFilledArray(int noSides, int length) {         int[] a = new int[noSides];         java.util.Arrays.fill(a, length);         return a;     }      public RegularPolygon(int id, Point center, int noSides, int length) {         super(id, center, noSides, getFilledArray(noSides, length));     } } 
like image 130
missingfaktor Avatar answered Sep 18 '22 16:09

missingfaktor


class Foo {     Foo(String str) { } }  class Bar extends Foo {     Bar(String str) {         // Here I am explicitly calling the superclass          // constructor - since constructors are not inherited         // you must chain them like this.         super(str);     } } 
like image 24
user2290013 Avatar answered Sep 20 '22 16:09

user2290013