class Demo {
int value1;
int value2;
Demo() {
value1 = 1;
value2 = 2;
System.out.println("Inside 1st....... Parent Constructor");
}
Demo(int a) {
value1 = a;
System.out.println("Inside 2nd Parent Constructor");
}
public void display() {
System.out.println("Value1 === " + value1);
System.out.println("Value2 === " + value2);
}
public static void main(
String args[]) {
DemoChild d1 = new DemoChild();
d1.display();
}
}
class DemoChild extends Demo {
int value3;
int value4;
DemoChild() {
this(5);// Need explanation why is it calling parent default constructor.
value3 = 3;
value4 = 4;
System.out.println("Inside the Constructor of Child");
}
DemoChild(int a) {
//super();
value3 = 5;
value4 = 6;
System.out.println("Inside the Constructor of 2nd Child");
}
public void display() {
System.out.println("Value1 === " + value1);
System.out.println("Value2 === " + value2);
System.out.println("Value1 === " + value3);
System.out.println("Value2 === " + value4);
}
}
Output of this program is
Inside 1stParent Constructor
Inside the Constructor of 2nd Child
Inside the Constructor of Child
Value1 === 1
Value2 === 2
Value1 === 3
Value2 === 4
I am expecting this(5) in DemoChild() constructor would call DemoChild(int a) . But as per the output it is making first super() call then calling DemoChild(int a). Can anyone please clarify doubt and explain the flow of constructor chaining
if possible.
Thanks
Rama