What is the order of calling constructors and initialization blocks, given the class hierarchy

First, all static blocks are called in order from the first static block of the root ancestor and up the hierarchy chain to the static blocks of the class itself.

Then the non-static initialization blocks of the root ancestor, the constructor of the root ancestor, and so on, down to the non-static blocks and the constructor of the class itself are called.

  • Parent static block(s) →
  • Child static block(s) →
  • Grandchild static block(s) →
  • Parent non-static block(s) →
  • Parent constructor →
  • Child non-static block(s) →
  • Child constructor →
  • Grandchild non-static block(s) →
  • Grandchild constructor

Example 1:

public class MainClass {

    public static void main(String args[]) {
        System.out.println(TestClass.v);
        new TestClass().a();
    }

}
public class TestClass {

    public static String v = "Some val";

    {
        System.out.println("!!! Non-static initializer");
    }

    static {
        System.out.println("!!! Static initializer");
    }

    public void a() {
        System.out.println("!!! a() called");
    }

}

Execution result:

!!! Static initializer
Some val
!!! Non-static initializer
!!! a() called

Example 2:

public class MainClass {

    public static void main(String args[]) {        
        new TestClass().a();
    }

}
public class TestClass {

    public static String v = "Some val";

    {
        System.out.println("!!! Non-static initializer");
    }

    static {
        System.out.println("!!! Static initializer");
    }

    public void a() {
        System.out.println("!!! a() called");
    }

}

Execution result:

!!! Static initializer
!!! Non-static initializer
!!! a() called

Why are we needed and what are the initialization blocks

Initialization blocks are code enclosed in curly braces and placed inside a class outside of a method or constructor declaration.

  • There are static and non-static initialization blocks.
  • The initialization block is executed before the class is initialized by the class loader or the class object is created using the constructor.
  • Several initialization blocks are executed in the order they appear in the class code.
  • The initialization block is capable of throwing exceptions if their declarations are listed in throws of all class constructors.
  • An initialization block can also be created in an anonymous class.

Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed