• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Final variables in anonymous inner-classes

 
Ranch Hand
Posts: 109
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello ranchers,

I know that anonymous inner-classes only can use
final local-variables, but I do not know the reason.



Why are non-final-instance-variables allowed,
but no non-final-local-variables?
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Why are non-final-instance-variables allowed,
but no non-final-local-variables?



It has to do with reachability of the variable. An inner class has a reference to it's outer class, so it is not possible for the outer class to be GC'ed, as long as the inner class is reachable.

This is not true for the method (the local variables). It is possible for the method to save the instance somewhere, or even return it, so, it is possible for the local variables to go out of scope (while the inner class still needs it), when the method returns.

This doesn't mean that the final local variables don't also go out of scope when the methods returns. All the method's local variables go out of scope upon return. What is happening is, since the variable is final, the compiler is making a copy of the variable for the inner class -- the inner class is not actually accessing the final local variable, but an internal private variable that contains the same value.

Henry
 
Oliver Rensen
Ranch Hand
Posts: 109
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Henry, thanks a lot.
reply
    Bookmark Topic Watch Topic
  • New Topic