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 ??? }
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++
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.
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.
Using the super Keyword to Call a Base Class Constructor in Java.
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)); } }
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With