Code:
Parent Class:
public class Parent {
int i = 10;
{
System.out.println(i);
}
public Parent(){
System.out.println("Parent");
}
}
Child Class:
public class Child extends Parent {
int j = 20;
{
System.out.println(j);
}
public Child() {
super();
}
}
Test Class:
public class ConstructorTest {
public static void main(String... args){
Child c = new Child();
}
}
Execution Flow(What I know):
Parent
Class. Child
Class. Parent
Class. Parent
constructor. Child
class. Child
constructor. Output:
10
Parent
20
My question is: in step 6- During execution of Child
constructor, why the parent constructor is not called again using super()
of child?
so why the output is not:
10
Parent
20
Parent
The super()
line has already taken effect in step 4, basically. Just super();
is implicit and would usually be removed. Typically you use explicit constructor chaining for:
Despite its position as the first line of the body of the child constructor, a this()
/ super()
statement is executed before the instance initializers. You should think of it as being somewhat separate from the rest of the body of the constructor.
See more on this question at Stackoverflow