我写了一段代码:
public class Child{
int y ;
private static final int z = getZ();
static {
System.out.println("The value of z is "+z);
}
public int getX(){
System.out.println("get x");
return 10;
}
public int getY(){
Child ch = new Child();
System.out.println("get y");
ch.y = getX();
return y;
}
public static int getZ(){
System.out.println("get z");
return new Child().getY();
}
public Child(){
System.out.println("Child constructor");
}
public static void main(String...args){
Child ch = new Child();
System.out.println("the value of z in main is "+z);
}
}
输出是:
get z
子构造函数
子构造函数
get y
得到 x
z 的值为 0
子构造函数
main 中 z 的值为 0
谁能解释一下为什么 z 的值为 0 而不是 10 ?
编辑:-谢谢大家,我得到了第一个问题的答案。我仍然有疑问,据我所知,静态块是在加载类之后和实例化类的第一个对象之前执行的。那么 SOP("The value of z is "+z) 应该在 SOP("Child constructor") 之前执行!不是吗?