Java中,类初始化的顺序分为:
父类静态代码块/父类静态变量,这两者的顺序取决于代码中的顺序
子类静态代码块/子类静态变量,同样的,这两者的顺序也是取决于代码中的顺序
父类普通代码块/父类普通变量,同样的,这两者的顺序也是取决于代码中的顺序
父类构造方法
子类普通代码块/子类普通变量,同样的,这两者的顺序也是取决于代码中的顺序
子类构造方法
测试代码
public class InitOrder {
public static void main(String[] args) {
new Son();
}
static Object printLog(String s) {
System.out.println(s);
return null;
}
}
class Father {
{
System.out.println("step 7 : Father normal block");
}
Object obj1 = InitOrder.printLog("step 8 : Father normal member");
static {
System.out.println("step 1 : Father static block");
}
static Object obj2 = InitOrder.printLog("step 2 : Father static member 1");
static Object obj3 = InitOrder.printLog("step 3 : Father static member 2");
public Father(){
System.out.println("step 9 : Father Constructor");
}
}
class Son extends Father {
Object obj1 = InitOrder.printLog("step 10 : Son normal member");
{
System.out.println("step 11 : Son normal block");
}
static Object obj2 = InitOrder.printLog("step 4 : Son static member 1");
static {
System.out.println("step 5 : Son static block");
}
static Object obj3 = InitOrder.printLog("step 6 : Son static member 2");
public Son(){
System.out.println("step 12 : Son Constructor");
}
}
测试结果
step 1 : Father static block
step 2 : Father static member 1
step 3 : Father static member 2
step 4 : Son static member 1
step 5 : Son static block
step 6 : Son static member 2
step 7 : Father normal block
step 8 : Father normal member
step 9 : Father Constructor
step 10 : Son normal member
step 11 : Son normal block
step 12 : Son Constructor