Possible Duplicate:
Why inner classes require “final” outer instance variables [Java]?
Why are only final variables accessible in anonymous class?
class Outer{
private String x = "instance variable";
void doStuff(){
String z = "local variable";
class Inner{
public void seeOuter(){
System.out.println("Outer x is : "+ x);
System.out.println("Local variable z is : " + z); //won't compile
}
}
}
}
Marking the local variable z as final fixes the problem :
final String z = "local variable"; //Now inner object can use it.
Can anyone please explain what is happening ?
I know exactly why it can not compile in case I am trying to access a non-final local variable.
Does making a local-variable final allows it to stay alive even if the method gets completed and local variable goes out of scope?
Does final local variables get stored on a heap instead of stack ?