Win a copy of Murach's MySQL this week in the JDBC and Relational Databases forum!
  • 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

Anonymous inner Classes accessing final variables

 
Ranch Hand
Posts: 415
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

When a write an inner class inside a method , it can access the variables in the enclosing method if and only if they are final ... Why is the compiler enforcing this ??

What might be the reason for java doing this ?? Is it that these Local Variables will be cached for Inner class usage ??
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your guess is exactly right. The inner class doesn't access the local variables of the enclosing method directly: the compiler actually sets things up so that the inner class has member variables of the given types, and when the inner class instance is constructed, the local variables are copied into those members. If the local variables weren't final, you could tell that this trick was being used, so to avoid confusion, we have the rule about final variables.

Why is the trick needed? Well, besides the fact that the JVM has no mechanism for accessing local variables in another stack frame, there's the issue that the inner class instance may very well still exist long after the enclosing method has returned. If the enclosing method returned, those local variables would be gone, so the inner class needs to use a copy of its own.
 
Get off me! Here, read this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic