我有一个这样的程序:
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
谁能解释这个问题。