我遇到了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);
}
}发布于 2015-11-03 15:17:26
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);
}
}发布于 2015-11-03 15:05:39
您应该将代码更改为:
public class Class {
private final int x;
public Class() {
x = 123;
}
...
}发布于 2015-11-03 15:07:59
你不应该声明三次,而应该声明一次。事实上,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);
}
}https://stackoverflow.com/questions/33502365
复制相似问题