jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Inner Classes in Methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Inner Classes in Methods" Watch "Inner Classes in Methods" New topic

Inner Classes in Methods

Shane Petrie

Joined: Apr 15, 2002
Posts: 2
Does anyone have an explanation as to why a class declared in a method can access local variables only if they are declared final.
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
If you have an inner class that is local to a method. Any objects of that class can access all of the local variales. Also, any instances of that class could potentially live beyond the life of the method.
When the method is done executing all of its local variables go out of scope but what if the object you created in it tried to accesss one of them after it was out of scope.
That's why they can only access final local variables which are stored separatley.
hope that helps

Sigfred Zamo
Ranch Hand

Joined: Mar 04, 2002
Posts: 44
Originally posted by Dave Vick:

..which are stored separatley.

when are final variables garbage collected then? If there are no more references to that inner class? Am I right?
[ April 15, 2002: Message edited by: Sigfred Zamo ]

Sigfred Zamo<br />Software Development<p><a href="http://www.sigfredo.ingenieros.net/index2.html" target="_blank" rel="nofollow">My page</a>
I agree. Here's the link: http://aspose.com/file-tools
subject: Inner Classes in Methods
It's not a secret anymore!