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超出範圍。 –