Method-Local inner class cannot access local variables because the instance of the method-local inner class may still alive after the method is over. But local variables will vanish once the local method is over. I learned that method-local inner class can access final local variable, does this mean final local variable still alive after the method is over?
-
3Care to post your example so that no one accidentally misunderstands your question? We are coders, and the Java code would give this a lot more clarity. – jamesmortensen May 20 '12 at 01:06
-
I think this is what you mean, and _no_ it doesn't work. http://ideone.com/LNg9w – Hunter McMillen May 20 '12 at 01:08
-
@HunterMcMillen The question is about method-local classes, not other methods. – Jeffrey May 20 '12 at 01:09
-
It's only alive after the method finishes if it's stored in a method-local inner class that was constructed. It certainly won't e.g. be available to future runs of the method. – Louis Wasserman May 20 '12 at 01:09
-
@Jeffrey Well I guess that shows how confusing the question was. Totally missed that. – Hunter McMillen May 20 '12 at 01:23
2 Answers
Sort of. Java anonymous inner classes act like "closures," that is, they "close" around the current local state. However, Java only lets these classes close around final variables. If it didn't, the local state of the variable could change, but the version held in the inner class would not, so it would be accessing an "out of date" instance. This could be confusing to a programmer.
Instead, Java requires that mutability be handled by the instance through methods, not variable reassignment. This leads to better clarity and allows for simpler debugging. For more information about why Java does this, see this answer.
Since the class still holds a reference to the variable, the answer to your question is yes, that instance will not be garbage collected until the inner class relinquishes ownership of the variable.

- 1
- 1

- 43,109
- 15
- 131
- 205
-
1*"This could be confusing to a programmer."* - More to the point, it would not be "like" a closure any more. You'd have an identifier name that has an observably different binding, depending on the lexical context. – Stephen C May 20 '12 at 02:16
No it doesn't. It means that a copy of the local variable is still alive, in the inner class instance. The 'final' just makes sure the two copies don't confusingly diverge in value.

- 305,947
- 44
- 307
- 483