Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner Classes in Methods

 
Shane Petrie
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Sigfred Zamo
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic