I have two classes Parent and Child
public class Parent {
public Parent() {
System.out.println("Parent Constructor");
}
static {
System.out.println("Parent static block");
}
{
System.out.println("Parent initialisation block");
}
}
public class Child extends Parent {
{
System.out.println("Child initialisation block");
}
static {
System.out.println("Child static block");
}
public Child() {
System.out.println("Child Constructor");
}
public static void main(String[] args) {
new Child();
}
}
The output of the above code will be
Parent static block
Child static block
Parent initialization block
Parent Constructor
Child initialization block
Child Constructor
Why does Java execute the code in that order? What are the rules that determine the execution order?
There are several rules in play
super();
before executing it's own constructor. Initialization block comes into play even before the constructor call, so that's why it is called first. So now your parent is created and the program can continue creating child class which will undergo the same process.Explanations:
- Static block of parent is executed first because it is loaded first and static blocks are called when the class is loaded.