Java Final 变量是否具有缺省值?
我有一个这样的程序:
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();
}
}
如果我尝试执行它,我得到编译器错误,因为:基于java默认值,我应该得到下面的输出对吗?variable x might not have been initialized
"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
任何人都可以解释一下这种行为。