Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding Method-local inner classes

 
Prasad Maddipatla
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,

We have a rule that " A method-local inner class cannot access the local variables in the method in which it is declared" but when we make local variables as final we can use them in the method local inner class. Can any body explain what the real difference when we make local varables as final so that they can be used in method-local inner classes.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When a method exits, its local variables are destroyed. But an instance of a local class might continue to exist after the method exits, and if it tried to access a local variable at that point, there would be a problem. On the other hand, if a local variable is final, then its value can be copied into the instance of the local class, and the instance can use it essentially as a constant.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic