This article allows you to thoroughly understand the initialization sequence of Java programs

This article allows you to thoroughly understand the initialization sequence of Java programs

scenes to be used

In a Java program, when an object is instantiated, all member variables of the object's class must be initialized first, and only when all class members are initialized, the constructor of the object's class will be called to create the object.

in principle

  1. Variables take precedence over blocks, and static take precedence over non-static.
  2. The parent class takes precedence over the derived class initialization.
  3. They are initialized in the order in which the member variables are defined. Even if the variable definitions are scattered among the method definitions, they are still initialized before any methods (including constructors) are called.

Initialization sequence

  • Parent class static variable
  • Parent class static code block
  • Subclass static variable
  • Subclass static code block
  • Non-static variables of the parent class
  • Parent non-static code block
  • Parent class constructor
  • Subclass non-static variables
  • Subclass non-static code block
  • Subclass constructor

Initialize sample code


class Base {

    public Base() {
        System.out.println(" ");
    }

    String b = " ";
    {
        System.out.println(b);
        System.out.println(" ");
    }

    static String a = " ";

    static {
        System.out.println(a);
        System.out.println(" ");
    }

    public static void A() {
        System.out.println(" ");
    }

}

class Derived extends Base {

    public Derived() {
        System.out.println(" ");
    }

    String b = " ";
    {
        System.out.println(b);
        System.out.println(" ");
    }

    static String a = " ";

    static {
        System.out.println(a);
        System.out.println(" ");
    }

    public static void A() {
        System.out.println(" ");
    }

    public static void main(String[] args) {
        Base.A();
        Derived.A();
        new Derived();
    }
}
 

Execute the three instructions in the main function separately, and the execution results are as follows.

Base.A()

  • Parent class static variable
  • Parent class static code block
  • Subclass static variable
  • Subclass static block
  • Normal static method of parent class

Derived.A()

  • Parent class static variable
  • Parent class static code block
  • Subclass static variable
  • Subclass static block
  • Subclass ordinary static method

new Derived()

  • Parent class static variable
  • Parent class static code block
  • Subclass static variable
  • Subclass static code block
  • Non-static variables of the parent class
  • Parent non-static code block
  • Parent class constructor
  • Subclass non-static variables
  • Subclass non-static code block
  • Subclass constructor