NIN*_*OOP 1 java static compile-time-constant static-initialization
我写了一段代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
get z
子构造函数
子构造函数
get y
get x
z的值为0
子构造函数
,main中的z值为0
任何人都可以解释为什么z的值是0而不是10?
编辑: -谢谢大家,我得到了第一个问题的答案.我仍然有一个疑问,据我所知,静态块是在加载类之后以及在实例化类的第一个对象之前执行的.那么SOP("z的值是"+ z)应该在SOP之前执行("子构造函数")!不是吗?
看看getY():
public int getY(){
Child ch = new Child();
System.out.println("get y");
ch.y = getX();
return y;
}
Run Code Online (Sandbox Code Playgroud)
前三行是无关的-它们不会改变的价值y在此情况下,这是被返回了什么.
你在坦率的意大利面条代码中创建了大量无意义的对象,在初始化你正在构造实例的同一个类时调用.我建议你尽量保持你的代码很多比这更简单.应该尽可能避免使用静态初始化器,更不用说那些遍布房屋的人不做任何有用的工作.