我有这样一个程序:
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();
}
}
如果我尝试执行它,我会得到编译器错误:变量 x 可能未被初始化。根据 Java 的默认值,我应该得到以下输出结果,对吗?
"Here x is 0".
最终变量会有默认值吗?
如果我将代码更改为以下内容:
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
能否有人解释一下这种行为。。