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);
}
}
Explanations I found to this :
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.