Java面试题 静态代码块 构造代码块 构造方法 的执行顺序

JAVA中的静态代码块 构造代码块 构造方法执行顺序:

静态代码块(类加载时执行)>>构造代码块>>构造方法

下面展示一个简单的例子,推荐大家动手运行一遍:

public class Main {

    public static void main(String[] args) {
        son s = new son();
    }
    
}

/*父类*/
public class father {
    private static String faterstaticArea = "father static area";

    static {
        System.out.println(faterstaticArea);
        System.out.println("father static block");
    }

    private String faterConstructorArea = "father Constructor area";
    {
        System.out.println(faterConstructorArea);
        System.out.println("father Constructor block");
    }

    father(){
        System.out.println("father constructor");
    }
}
//son继承father
public class son extends father{
    private static String sonStaticArea = "son static area";

    static {
        System.out.println(sonStaticArea);
        System.out.println("son static block");
    }

    private String sonConstructorArea = "son Constructor area";
    {
        System.out.println(sonConstructorArea);
        System.out.println("son Constructor block");
    }

    son(){
        System.out.println("son constructor");
    }
}
//运行结果
father static area  //首先加载父类
father static block
son static area     //加载子类
son static block
father Constructor area  //构造父类
father Constructor block
father constructor         //执行构造代码块再执行构造方法
son Constructor area     //构造子类
son Constructor block
son constructor              //执行构造代码块再执行构造方法
原文地址:https://www.cnblogs.com/joe2047/p/9846003.html