我遇到了final
关键字,它显然锁定了一个值,因此以后无法更改。但是当我尝试使用它时,变量x
仍然会被更改。我在某个地方出错了吗?
public class Class {
// instance variable
private int x;
public Class() {
// initialise instance variables
final int x = 123;
}
public void sampleMethod() {
// trying to change it using final again
final int x = 257;
System.out.println(x);
}
public void sampleMethod2() {
// trying to change it using without using final
x = 999;
System.out.println(x);
}
}
答案 0 :(得分:3)
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);
}
}
答案 1 :(得分:2)
您可以将代码更改为:
public class Class {
private final int x;
public Class() {
x = 123;
}
...
}
答案 2 :(得分:1)
您应该声明一次,而不是声明三次。
事实上sampleMethod2()
不是必需的
public class Class {
// instance variable
private final int x;
public Class() {
// initialise instance variables
x = 123;
}
public void sampleMethod() {
// You will get error here
x = 257;
System.out.println(x);
}
}