new一个对象时,该对象的初始化顺序如下 :
父类中的静态成员变量 父类中的静态代码块 子类中的静态成员变量 子类中的静态代码块 父类中的非静态变量 父类中的非静态代码块 父类构造函数 子类中的非静态成员变量 子类中的非静态代码块 子类构造函数
看如下例子(根据上面的初始化顺序,猜一下输出的顺序)
class Money {
public Money() {
System.out.println("money");
}
}
class Father {
public static int age = 30;
public Money m = new Money();
public String name = "father";
public Father() {
System.out.println("father constructor start");
System.out.println(age);
age += 5;
System.out.println(age);
System.out.println("father constructor end");
}
static {
System.out.println("father static block start");
System.out.println(age);
age += 5;
System.out.println(age);
System.out.println("father static block end");
}
}
class Son extends Father {
public Money m = new Money();
public static int age = 10;
public String name = "son";
public Son() {
System.out.println("son constructor start");
System.out.println(age);
age += 5;
System.out.println(age);
System.out.println("son constructor end");
}
static {
System.out.println("son static block start");
System.out.println(age);
age += 5;
System.out.println(age);
System.out.println("son static block end");
}
}
output:father static block start
30
35
father static block end
son static block start
10
15
son static block end
money
father constructor start
35
40
father constructor end
money
son constructor start
15
20
son constructor end