• 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
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

FAQ Explanations

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

May I ask to explain me following point from FAQ:

Local classes cannot access non-final variables.



Thank you.

 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There's a good detailed explanation for this in the K&B SCJP6 book on page 671, in the section Method-Local Inner Classes

From reading the above section:

Method-Local inner classes are declared inside a method.

Variables declared inside a method reside on the stack ( not on the heap) and so, they are temporary.

But the object created from the Method-Local inner class can exist on the heap long after the method completes, so it needs to guarantee that whatever variables it is accessing still exist on the heap ( I think final variables declared inside a method exist permanently and that's why it can access only final variables and not regular variables declared inside the method.)

If the variable accessed inside the method-local inner class is a variable from the outer class (not a method variable) , it need not be declared final. The outer object's variables exist on the heap.

Only if the variable accessed in the method-local inner class is a variable declared inside the method, then that variable can be accessed only if it is final , otherwise the code throws a compiler error.




 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic