The local inner class method can only access the final local variable. Why?

Possible duplicate:
Why do inner classes require "final" variables of an external instance [Java]?
Why are only final variables available in an 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 explain what is happening?

I know exactly why it cannot compile if I try to access a non-finite local variable. Does the ending of the local variable make it stay alive even if the method terminates and the local variable goes out of scope?

Are the last local variables stored in the heap instead of the stack?

+7
source share
2 answers

They can use local variables and function parameters, but only those that are declared final , because the local class instance must support a separate copy of the variable, since it may not work. Thus, there is no confusion of two mutable variables with the same name in the same scope, the variable is forced to be unmodifiable.

+10
source

Mark local variable z final, fix the problem: Can someone explain what is going on?

You have a local method class that is allowed to access the final local variable in the scope that it created.

Does the ending of the local variable make it stay alive even if the method terminates and the local variable goes out of scope?

final means that it cannot be changed. Nothing more.

Are the last local variables stored in the heap instead of the stack?

All variables are allocated on the stack, final or not.

I know exactly why it cannot compile if I try to access a non-finite local variable.

Perhaps you should think about it, because it is not clear that this is generally so.

A nested class can "access" the final variable, since they are automatically copied as fields of the object. It does not support non-final fields, since they can be changed either by a method or by a class, and this is not supported, since there are actually two different fields / variables.

+2
source

All Articles