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?
(In your code the parent static blocks will be executed first and then the child class static blocks.)
In your code when you create a Child object:
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.Here is what I found while preparing for a certification.
While we run a class, first static blocks/ static variable initialisation happens. If multiple static blocks are there, it will execute it in the order in which it appears,
Then it will execute init blocks/ instance variable initialisation.If multiple init blocks/ variable initialisation are there, it will execute it in the order in which it appears,
Afterwards it will look into the constructor.
Static block gets executed when a class is loaded into JVM. While init block gets copied into the Constructor whose object will be created and runs before creation of object.
First - run child class only (comment the extend clause) to see the simple flow.
second - go to Static block vs. initializer block in Java? & read the accepted answer over there.
Edit:
control flow is-
static block -> Initialization block -> and finally Constructor.
static block -> This static block will be get executed only once when the control come to the class.(JVM Load this class)
Initialization block -> This Initialization block will be get executed whenever a new object Created for the Class (It will be executed from second statement of the Constructor then following constructor statements- remember First statement of the Constructor will be Super()/this())
Constructor -> This will be get whenever a new object is created.