Class的构造顺序可以从编译的角度去理解,突然想到一个非常好的例子来说明这个问题
package com.cachetian.scjp;
public class MyChildObj {
public MyChildObj() {
System.out.println("My Child Obj Constructes");
}
}
package com.cachetian.scjp;
public class MyObj extends MyFatherObj{
protected MyChildObj child = new MyChildObj();
public MyObj() {
System.out.println("My Obj Constructed");
}
public static void main(String[] args) {
new MyObj();
}
}
package com.cachetian.scjp;
public class MyFatherObj extends MyGrandFatherObj{
public MyFatherObj() {
System.out.println("My Father Obj Constructed");
}
}
package com.cachetian.scjp;
public class MyUncleObj {
public MyUncleObj() {
System.out.println("My Uncle Constructed");
}
}
package com.cachetian.scjp;
public class MyGrandFatherObj {
protected MyUncleObj myUncle = new MyUncleObj();
public MyGrandFatherObj() {
System.out.println("My Grandfather Constructed");
}
}
运行结果:
My Uncle Constructed
My Grandfather Constructed
My Father Obj Constructed
My Child Obj Constructes
My Obj Constructed