• 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

Method-Local Inner Class question

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

In K&B 6, Ch.8 p.671 (Method-Local Inner Classes) it states that the Inner Class Object can't use the local variables of the method that it's in

Because the local variables aren't guaranteed to be alive as long as the method-local inner class object... ...Unless the local variables are marked final.



I don't understand why marking the local variable as final would make a difference. My understanding is that marking an object reference variable as final means that you can't assign another object to that reference variable, but it has no effect on the variable's scope.

I wrote this code to test:



the output is:



I can understand the first output as the StringBuilder object 'bob' is on the stack. But surely after the go() method has run, the stack frame is popped from the stack (if thats the right terminology) and no reference to 'bob' exists. So when the goAgain() method runs, I'm not sure how the doStuff method manages to access an object to which no reference exists. But it does, so there's something I'm not understanding here.

Anyone care to enlighten me?

Thanks in advance

Joe
 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This has been discussed many times before like here and here...
 
Joe Lemmer
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ankit,

Thank you for those links. It makes sense now. Apologies for not doing a proper search.
 
Ankit Garg
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Joe Lemmer wrote:Apologies for not doing a proper search.


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