Java代码块(静态和非静态)在子父类中的执行顺序

话不多说,直接上代码:

/**
 * @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();
    }
}

输出结果:

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

代码分析:
可以看出,静态代码块内的语句由父类到子类最先执行,且只执行一次,这是因为静态代码块虽类的加载而加载;
之后每创建一次对象的时候,由父及子,先执父类中的普通代码块,再执行父类中的构造器,然后在执行子类中的普通代码块,再执行子类中的构造器。

猜你喜欢

转载自blog.csdn.net/MrYushiwen/article/details/109754257