我有以下代码:
public class BookLib {
void f() {
final int x = 5; // Line 1
class MyCLass {
void print() {
System.out.println(x);
}
}
}
}
我不明白为什么在这种情况下(第 1 行)要使用 final 变量?
最佳答案
您在这里创建了一个内部类。由于此类对象的生命周期可能比方法调用的运行时间长得多(即对象在方法返回后仍然存在很长时间),它需要“保留”局部变量的状态可以访问。
这种保留是通过在内部类中创建一个(不可见的、合成的)副本并自动将对局部变量的所有引用替换为对该副本的引用来完成的。当在创建内部类对象后修改局部变量时,这可能会导致奇怪的效果。
为避免这种情况,要求您以这种方式访问的所有局部变量都是final
:这确保局部变量永远只有一个可能的值,并且不会观察到不一致。
此特定规则可在§8.1.3 Inner Classes and Enclosing Instances 中找到的 the JLS :
Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.
关于java - 关于Java中局部final变量的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5947352/