This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Method-Local Inner Class question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Method-Local Inner Class question" Watch "Method-Local Inner Class question" New topic
Author

Method-Local Inner Class question

Joe Lemmer
Ranch Hand

Joined: Oct 24, 2008
Posts: 171
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


OCPJP 85%
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

This has been discussed many times before like here and here...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Joe Lemmer
Ranch Hand

Joined: Oct 24, 2008
Posts: 171
Hi Ankit,

Thank you for those links. It makes sense now. Apologies for not doing a proper search.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

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

NoNeedToSaySorry
 
wood burning stoves
 
subject: Method-Local Inner Class question