先说结论,初始化顺序如下:
- 基类静态代码块,基类静态成员字段(并列优先级,按照代码中出现的先后顺序执行,且只有第一次加载时执行);
- 派生类静态代码块,派生类静态成员字段(并列优先级,按照代码中出现的先后顺序执行,且只有第一次加载时执行);
- 基类普通代码块,基类普通成员字段(并列优先级,按代码中出现先后顺序执行);
- 基类构造函数;
- 派生类普通代码块,派生类普通成员字段(并列优先级,按代码中出现先后顺序执行);
- 派生类构造函数。
代码示例如下:
(1)派生类和基类代码
class Log {
public static String initLog(String log) {
System.out.println(log);
return null;
}
}
/**
* 基类
*/
class Base {
static {
System.out.println("Base Static Block 1");
}
private static String staticValue = Log.initLog("Base Static Fiels");
static {
System.out.println("Base Static Block 2");
}
{
System.out.println("Base Normal Block 1");
}
private String value = Log.initLog("Base Normal Field");
{
System.out.println("Base Normal Block 2");
}
Base() {
System.out.println("Base Constructor");
}
}
/**
* 派生类
*/
public class Derived extends Base {
static {
System.out.println("Static Block 1");
}
private static String staticValue = Log.initLog("Static Fiels");
static {
System.out.println("Static Block 2");
}
{
System.out.println("Normal Block 1");
}
private String value = Log.initLog("Normal Field");
{
System.out.println("Normal Block 2");
}
Derived() {
System.out.println("Derived Constructor");
}
}
(2)执行函数
/**
* 主线程
*/
public class Main {
public static void main(String[] args) {
Derived derived = new Derived();
}
}
最终控制台输出: