public class Class {
// instance variable
private int x; // <-- This variable is NOT final.
public Class() {
// initialise instance variables
final int x = 123; // <-- This is NOT the instance variable x, but rather hiding this.x with a method local variable called 'x'
}
public void sampleMethod() {
// trying to change it using final again
final int x = 257; // <-- This is NOT the instance variable x, but rather hiding this.x with a method local variable called 'x'
System.out.println(x);
System.out.println(this.x); // see!
}
public void sampleMethod2() {
// trying to change it using without using final
x = 999; // This changes this.x, but this.x IS NOT final.
System.out.println(x);
}
}
现在让我们看看我们如何真正创建一个最终的变量:
public class ClassWithFinalInstanceVariable {
private final int x;
public ClassWithFinalInstanceVariable() {
this.x = 100; // We can set it here as it has not yet been set.
}
public void doesNotCompileIfUncommented() {
// this.x = 1;
// If the line above is uncommented then the application would no longer compile.
}
public void hidesXWithLocalX() {
int x = 1;
System.out.println(x);
System.out.println(this.x);
}
}
因为你设置的方法中的局部变量''x'和sampleMethod'你的构造函数是最终的,而不是类变量'x'。 – SomeJavaGuy
因为在方法中声明的变量是局部变量,所以你必须为整个类变量final而不仅仅是构造函数/方法。例如,当构造函数完成时,最终的int x = 123超出范围。 –