【发布时间】:2014-09-19 08:55:32
【问题描述】:
我有一个这样的程序:
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".
final 变量会有默认值吗?
如果我像这样更改我的代码,
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
谁能解释一下这种行为..
【问题讨论】: