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

Solution 1:

I learn visually, so here's a visual representation of order, as a SSCCE:

public class Example {

    static {
        step(1);
    }

    public static int step_2 = step(2);
    public int step_8 = step(8);

    public Example(int unused) {
        super();
        step(10);
    }

    {
        step(9);
    }

    // Just for demonstration purposes:
    public static int step(int step) {
        System.out.println("Step " + step);
        return step;
    }
}
public class ExampleSubclass extends Example {

    {
        step(11);
    }

    public static int step_3 = step(3);
    public int step_12 = step(12);

    static {
        step(4);
    }

    public ExampleSubclass(int unused) {
        super(step(7));
        step(13);
    }

    public static void main(String[] args) {
        step(5);
        new ExampleSubclass(step(6));
        step(14);
    }
}

This prints:

Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8
Step 9
Step 10
Step 11
Step 12
Step 13
Step 14

Keep in mind that the order of the static parts matters; look back at the difference between the order of Example's static stuff and ExampleSubclass's.

Also note that the instance initialization block is always executed immediately after the super() call in the constructor (even if that call is implied/omitted), no matter the order. However, order does matter between an initialization block and a field initializer.

Solution 2:

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.