Details of the element initialization sequence in a Java class

  • 2020-04-01 02:12:22
  • OfStack


public class Test4 {
    @Test
    public void test(){
        child child = new child();
    }
}
class parent{
    public static String parentStaticField = " Parent class static variables ";
    public String parentNormalField =" Superclass ordinary variable ";
    static {
        System.out.println(parentStaticField);
        System.out.println(" Parent class static block ");
    }

    {
        System.out.println(parentNormalField);
        System.out.println(" Parent normal block ");
    }

    public parent(){

        System.out.println(" Parent class constructor ");
    }
}
class child extends parent{
    public static String childStaticField = " Subclass static variable ";
    public String childNormalField =" Subclass ordinary variable ";
    static {
        System.out.println(childStaticField);
        System.out.println(" Subclass static block ");
    }

    {
        System.out.println(childNormalField);
        System.out.println(" Subclass normal block ");
    }

    public child(){
        System.out.println(" Subclass constructor ");
    }
}

Output:


 Parent class static variables 
 Parent class static block 
 Subclass static variable 
 Subclass static block 
 Superclass ordinary variable 
 Parent normal block 
 Parent class constructor 
 Subclass ordinary variable 
 Subclass normal block 
 Subclass constructor 

Execution process:

1. When new child is executed, the loader looks for the compiled code for the child class (that is, the child.class file). During the load, the loader notices that it has a base class, so it loads the base class again. This will happen whether you create a base class object or not. If the base class has a base class, the second base class will be loaded, and so on.

Perform static initialization of the base class, then static initialization of the next derived class, and so on. This order is important because the "static initialization" of a derived class can depend on the correct initialization of a base class member.

3. When all the necessary classes have been loaded, create the child class object.

4. If the child class has a parent class, the constructor of the parent class is called, and super can be used to specify which constructor to call.

Base classes are constructed in the same process and in the same order as derived classes. The variables in the base class are initialized in literal order, and the rest of the base class's constructor is executed.

5. Initialize subclass member data in the order they are declared, executing the rest of the subclass constructor.


Related articles: