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

90,372

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.

Solution 3

  • Static init blocks are executed at the time of class loading.
  • In the class hierarchy the order for execution of static init blocks will start from top level class.
  • In a class the order for the execution of static block is from top to bottom.
  • Above rule apply regardless of where the static block is present within the class.

(In your code the parent static blocks will be executed first and then the child class static blocks.)

  • Instance init blocks will be executed after the call to the super(); in the constructor.
    • Always super(); is the very first statement in a default constructor.

In your code when you create a Child object:

  • The default constructor of the Child class get executed.
  • It will call to the super(); constructor.
  • Then the super class constructor is executed.
  • The Parent class will execute its super(); call.
  • After that the instance init blocks in the Parent class are executed.(From top to bottom).
  • Then the code within the constructor is executed (if any).
  • Then it will return to the Child class and execute the Child class instance init blocks.
  • Finally the code in the child constructor get executed (If exists).

Solution 4

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:

  1. Execution happens in SIC way - Static, (non static) Initializer & Constructor.
  2. (Non static) Initializer are copied into every constructor - At the TOP! (hence lines 3/4/5/6)
  3. Before a class is initialized, its direct superclass must be initialized - http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4 (hence parent static block appears first).

Solution 5

Static block in java is executed before main method. If we declare a Static block in java class it is executed when class loads. This is initialize with the static variables. It is mostly used in JDBC. Static block in java is executed every time when a class loads. This is also known as Static initialization block. Static block in java initializes when class load into memory , it means when JVM read the byte code. Initialization can be anything; it can be variable initialization or anything else which should be shared by all objects of that class. Static block is a normal block of code enclosed in braces { } and is preceded by static keyword.

so static block executed first.

Instance Initialization Blocks: Runs every time when the instance of the class is created.

so next Initialization block executed when instance of the class is created.

then Constructor executed

Share:
90,372
CKR666
Author by

CKR666

Updated on July 08, 2022

Comments

  • CKR666
    CKR666 almost 2 years

    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?