• 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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

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.
 
Alas, poor Yorick, he knew this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic