我有一个类,我试图在初始化之前打印一个最终变量并得到如下的编译错误(这是预期的结果,因为只允许通过方法使用final变量的默认值),
public class Test{
private final int x;
Test(){
System.out.println("Here x is " + x); // Compile time error: variable 'x' might not be initialized
x = 7;
System.out.println("Here x is " + x);
System.out.println("const called");
}
public static void main(String[] args) {
Test test = new Test();
}
}
但令人惊讶的是,使用此引用打印x作为this.x如下所示并打印0,
public class Test{
private final int x;
Test(){
System.out.println("Here x is " + this.x); // Not a Compile time error and prints 0
x = 7;
System.out.println("Here x is " + x);
System.out.println("const called");
}
public static void main(String[] args) {
Test test = new Test();
}
}
任何人都可以解释为什么代码表现得像这样?