This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Inner Classes in Methods" Watch "Inner Classes in Methods" New topic
Author

Inner Classes in Methods

Shane Petrie
Greenhorn

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
Shane
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


Dave
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>
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Inner Classes in Methods