私はコードを書きました:
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
get x
z の値は 0
子コンストラクタ
main の z の値は 0
z の値が 10 ではなく 0 である理由を誰か説明してもらえますか?
編集:-皆さん、ありがとうございます。最初の質問に対する回答が得られました。クラスがロードされた後、クラスの最初のオブジェクトがインスタンス化される前に静的ブロックが実行されることを知る限り、私にはまだ疑問があります。それでは、SOP("The value of z is "+z)" は SOP("Child constructor") の前に実行されるべきでした! そうじゃない?