一.测试单类的初始化顺序
public class ClassInitOrderTest {
//静态变量 public static String staticField = "static field"; //静态代码块 static { System.out.println(staticField); System.out.println("static block"); } //成员变量 private String field = "member field"; //非静态代码块 { System.out.println(field); System.out.println("non-static block"); } //构造器 public ClassInitOrderTest() { System.out.println("constructor"); } public static void main(String[] args) { new ClassInitOrderTest(); } }
程序输出结果:
static field static block member field non-static block constructor
结论:
静态变量 > 静态初始块 > 成员变量 > 非静态初始块 > 构造器
二.测试继承中类的初始化顺序
class Parent { //父类静态变量 private static String parentStaticField = "parent static field"; //父类静态代码块 static { System.out.println(parentStaticField); System.out.println("parent static block"); } //成员变量 private String parentField = "parent member field"; //非静态代码块 { System.out.println(parentField); System.out.println("parent non-static block"); } //父类构造器 public Parent() { System.out.println("parent constructor"); } } public class Child extends Parent { //子类静态变量 private static String childStaticField = "child static field"; //子类静态代码块 static { System.out.println(childStaticField); System.out.println("child static block"); } //子类成员变量 private String childField = "child member field"; //子类非静态代码块 { System.out.println(childField); System.out.println("child non-static block"); } //子类构造器 public Child() { System.out.println("child constructor"); } public static void main(String[] args) { new Child(); } }
输出结果:
parent static field parent static block child static field child static block parent member field parent non-static block parent constructor child member field child non-static block child constructor
结论:
父类静态变量 > 父类静态初始块 > 子类静态变量 > 子类静态初始块 > 父类成员变量 > 父类非静态初始块 > 父类构造器 > 子类成员变量 > 子类非静态初始块 > 子类构造器