Why local inner class object cannot use the local variables of the method the inner class is in?

The local variables of the method live on the stack, and exist only for
the lifetime of the method. You already know that the scope of a local variable is
limited to the method the variable is declared in. When the method ends, the stack
frame is blown away and the variable is history. But even after the method
completes, the inner class object created within it might still be alive on the heap if, for example, a reference to it was passed into some other code and then stored in an instance variable. Because the local variables aren't guaranteed to be alive as long as the method-local inner class object, the inner class object can't use them. Unless the local variables are marked final! The following code attempts to access a local variable from within a method-local inner class.
class MyOuter {
private String x = "Outer";
void doStuff() {
String z = "local variable";
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
System.out.println("Local variable z is " + z); // Won't Compile!
}}}}
Compiling the preceding code really upsets the compiler:
MyOuter2.java:8: local variable z is accessed from within inner class;
needs to be declared final.
So the modified program is:
class MyOuter {
void doStuff() {
final String z = "local variable";
class MyInner {
public void seeOuter() {
System.out.println("Local variable z is " + z);
}}
MyInner inner=new MyInner();
inner.seeOuter();
}
public static void main(String[] args){
MyOuter obj=new MyOuter();
obj.doStuff();
}}

No comments:

Post a Comment