This example will help you to understand the constructor chaining along with the inheritance concept in java. The following java code snippet is the super class which has 3 set of constructors with different parameters along with getVolume() method.
public class ParentCube {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
ParentCube() {
this(10, 10);
System.out.println("Finished with Default Constructor of ParentCube");
}
ParentCube(int l, int b) {
this(l, b, 10);
System.out
.println("Finished with Parameterized Constructor having 2 params of ParentCube");
}
ParentCube(int l, int b, int h) {
length = l;
breadth = b;
height = h;
System.out
.println("Finished with Parameterized Constructor having 3 params of ParentCube");
}
}
Now, we will create the sub class which will extend the super class and will call the super class constructor from its own constructor. Once after we see the output of the following program, it will be clear how the execution flow is moving.
public class ChildCube extends ParentCube {
int weight;
ChildCube() {
super();
weight = 10;
System.out
.println("Finished with Parameterized Constructor having 0 param of ChildCube");
}
ChildCube(int l, int b) {
this(l, b, 10);
System.out
.println("Finished with Parameterized Constructor having 2 params of ChildCube");
}
ChildCube(int l, int b, int h) {
super(l, b, h);
weight = 20;
System.out
.println("Finished with Parameterized Constructor having 3 params of ChildCube");
}
public static void main(String[] args) {
ChildCube childObj1 = new ChildCube();
ChildCube childObj2 = new ChildCube(10, 20);
System.out.println("Volume of childObj1 is : " + childObj1.getVolume());
System.out.println("Weight of childObj1 is : " + childObj1.weight);
System.out.println("Volume of childObj2 is : " + childObj2.getVolume());
System.out.println("Weight of childObj2 is : " + childObj2.weight);
}
}
Output
Finished with Parameterized Constructor having 3 params of ParentCube
Finished with Parameterized Constructor having 2 params of ParentCube
Finished with Default Constructor of ParentCube
Finished with Parameterized Constructor having 0 param of ChildCube
Finished with Parameterized Constructor having 3 params of ParentCube
Finished with Parameterized Constructor having 3 params of ChildCube
Finished with Parameterized Constructor having 2 params of ChildCube
Volume of childObj1 is : 1000
Weight of childObj1 is : 10
Volume of childObj2 is : 2000
Weight of childObj2 is : 20