6

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?

5
  • 3
    Care 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. Commented May 20, 2012 at 1:06
  • I think this is what you mean, and no it doesn't work. ideone.com/LNg9w Commented May 20, 2012 at 1:08
  • @HunterMcMillen The question is about method-local classes, not other methods. Commented 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. Commented May 20, 2012 at 1:09
  • @Jeffrey Well I guess that shows how confusing the question was. Totally missed that. Commented May 20, 2012 at 1:23

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"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.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.