The execution order of Java code blocks (static and non-static) in the child parent class

Not much to say, just go to the code:

/**
 * @Author: YuShiwen
 * @Date: 2020/11/17 9:01 PM
 * @Version: 1.0
 */

class Root{
    
    
    static{
    
    
        System.out.println("Root static block");
    }
    {
    
    
        System.out.println("Root no static block");
    }
    public Root(){
    
    
        super();
        System.out.println("Root no parameter");
    }
}

class Mid extends Root{
    
    
    static{
    
    
        System.out.println("Mid static block");
    }
    {
    
    
        System.out.println("Mid no static block");
    }
    public Mid(){
    
    
        super();
        System.out.println("Mid no parameter");
    }

    public Mid(String msg){
    
    
        this();
        System.out.println("Mid constructor:"+msg);
    }
}

class Leaf extends Mid{
    
    
    static{
    
    
        System.out.println("Leaf static block");
    }
    {
    
    
        System.out.println("Leaf no static block");
    }
    public Leaf(){
    
    
        super("YuShiwen");
        System.out.println("Leaf no parameter");
    }
}

public class LeafTest {
    
    
    public static void main(String[] args) {
    
    
        new Leaf();
        System.out.println();
        new Leaf();
    }
}

Output result:

Root static block
Mid static block
Leaf static block
Root no static block
Root no parameter
Mid no static block
Mid no parameter
Mid constructor:YuShiwen
Leaf no static block
Leaf no parameter

Root no static block
Root no parameter
Mid no static block
Mid no parameter
Mid constructor:YuShiwen
Leaf no static block
Leaf no parameter

Process finished with exit code 0

Code analysis: It
can be seen that the statements in the static code block are executed first from the parent class to the child class, and only executed once. This is because the static code block is loaded despite the loading of the class;
afterwards, every time an object is created, Parents and children, first execute the ordinary code block in the parent class, and then execute the constructor in the parent class, then execute the ordinary code block in the subclass, and then execute the constructor in the subclass.

Guess you like

Origin blog.csdn.net/MrYushiwen/article/details/109754257