• 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
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

do inner classes need final local vars?

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following code did not compile and said that the local var x needs to be final.. Why does it need to be final? Any particular reasons?


Thanks.
(edited by Cindy to add [ code][ /code] tags)
[ December 13, 2002: Message edited by: Cindy Glass ]
 
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In that situation x would need to be final because it is a method local variable that normally would be cleaned up from the stack as the method returns. Your inner class has a reference to it, and basically (although I don't really understand the details), the final allows the compiler to give you a copy of the value that your class can use. For object references, the compiler needs to know that the object your reference refers to will not be changed.
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you make the variable final, instead of placing the value of x in the stack for method1 (which gets zapped as soon as the method is over) the variable value gets put in the Constant Pool which sticks around and is therefore available so that the m object can use it even after method1 is over.
In this case that is not much of a deal because as soon as method1 is over the the object referenced by m is available for the GC, however it is possible for such a method to return such an object or to have a variable outside the method hold a reference to it. In that case the MyClass object could live for a LOT longer than the method in which it was created.
 
I'm a lumberjack and I'm okay, I sleep all night and work all day. Lumberjack ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic