私はこのようなプログラムを持っています:
class Test {
final int x;
{
printX();
}
Test() {
System.out.println("const called");
}
void printX() {
System.out.println("Here x is " + x);
}
public static void main(String[] args) {
Test t = new Test();
}
}
それを実行しようとすると、次のようなコンパイラエラーが発生します:variable x might not have been initialized
Javaのデフォルト値に基づいて、以下の出力を正しく取得する必要がありますか?
"Here x is 0".
最終変数にはdafault値がありますか?
このようにコードを変更すると、
class Test {
final int x;
{
printX();
x = 7;
printX();
}
Test() {
System.out.println("const called");
}
void printX() {
System.out.println("Here x is " + x);
}
public static void main(String[] args) {
Test t = new Test();
}
}
次のように出力されます:
Here x is 0
Here x is 7
const called
誰かがこの振る舞いを説明できますか。