In what order do static blocks and initialization blocks execute when using inheritance?

CKR666 picture CKR666 · Oct 24, 2013 · Viewed 76.9k times · Source

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?

Answer

Petr Mensik picture Petr Mensik · Oct 24, 2013

There are several rules in play

  • static blocks are always run before the object is created, so that's why you see print messages from both parents and child static blocks
  • now, when you are calling constructor of the subclass (child), then this constructor implicitly calls 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:

  1. Static block of parent is executed first because it is loaded first and static blocks are called when the class is loaded.