Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method-Local Inner Class question

 
Joe Lemmer
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • 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
 
Ankit Garg
Sheriff
Posts: 9527
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • 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
  • 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: 9527
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe Lemmer wrote:Apologies for not doing a proper search.

NoNeedToSaySorry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic