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– jamesmortensen2012-05-20 01:06:44 +00:00Commented May 20, 2012 at 1:06
-
I think this is what you mean, and no it doesn't work. ideone.com/LNg9wHunter McMillen– Hunter McMillen2012-05-20 01:08:06 +00:00Commented May 20, 2012 at 1:08
-
@HunterMcMillen The question is about method-local classes, not other methods.Jeffrey– Jeffrey2012-05-20 01:09:14 +00:00Commented May 20, 2012 at 1: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– Louis Wasserman2012-05-20 01:09:20 +00:00Commented May 20, 2012 at 1:09
-
@Jeffrey Well I guess that shows how confusing the question was. Totally missed that.Hunter McMillen– Hunter McMillen2012-05-20 01:23:39 +00:00Commented May 20, 2012 at 1: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.