问题描述
方法中定义的内部类无法访问方法的局部变量,除非这些局部变量标记为 final
。我看过其他stack-overflow和java code ranch中的帖子但是它们似乎都没有完全回答关于标记变量final如何允许内部类访问方法中的局部变量的问题。
An inner class defined inside a method cannot access the method's local variables unless these local variables are marked final
.I've looked at other posts in stack-overflow and java code ranch but none of them seem to be exactly answering the question as to how marking variables final allows inner class to access local variables in the method.
class MyOuter {
private String x = "Outer";
void fly(final int speed) {
final int e = 1;
class FlyingEquation {
public void seeOuter()
{
System.out.println("Outer x is " + x);
}
public void display()
{
System.out.println(e);// line 1
System.out.println(speed);// line 2
}
}
FlyingEquation f=new FlyingEquation();
f.seeOuter();
f.display();
}
public static void main(String args[])
{
MyOuter mo=new MyOuter();
mo.fly(5);
}
}
我发现的解释:
局部变量存储在堆栈中,一旦方法调用完成,就会弹出堆栈并且局部变量不可访问,而最终局部变量存储在内存的数据部分中,即使在方法调用结束后也可能允许 JVM
访问它们。内存的数据部分在哪里?我相信所有局部变量final = not 都存储在堆栈中。当从堆栈中删除该方法时,最终变量将被删除。最终变量中的值是否与堆中的对象一起存储?
local variables are stored on stack and as soon as the method call finishes the stack is popped up and local variables are inaccessible whereas final local variables are stored in data section of memory potentially allowing JVM
to access them even after the end of the method call. Where is the data section of memory
? I believe all local variables final or not are stored on the stack.When the method is removed from the stack the final variable will be removed with it. Is it that the value in the final variable is stored with the object in the heap ?
它不支持非最终字段,因为它们可以通过方法或类,这是不支持的,因为实际上有两个不同的字段/变量。
It does not support non-final fields as they could be changed, either by the method or the class and this is not supported because in reality there are two different fields/variables.
推荐答案
在实例化内部class,当方法和类都在作用域内时,内部类将复制作为常量的变量,这意味着该方法可以超出范围,因为内部类只使用变量的副本。
。
During instantiation of the inner class, when both the method and the class are in scope, the inner class will make a copy of the variables which are constants, which means that the method can go out of scope, since the inner class is only using a copy of the variable.Check out this article.
这篇关于如何将变量标记为最终允许内部类访问它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!