• 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
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Method-Local Inner Classes and the final local variable

 
Richard Parker
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

According to the K&B book (chapter 8), a Method-Local Inner Class cannot use variables declared within the method unless those variables are marked final.

This is because the Method-Local Inner Class object might live longer on the heap than the local variable in the method would live on the stack.
-

This is all fine and dandy, but what makes a final variable so different?

Sure - the keyword final makes it impossible to reinitialize that variable once it has been initialized - but doesn't a final variable also live on the stack and therefore might still have a shorter life than the Method-Local Inner Class object?

Thanks,
Richard
 
marc weber
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because the variable is final, its value can be copied into the instance. Then when the method exits (and its variables are destroyed), the instance still has that value.
 
Richard Parker
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ah - yes, thank you mark

"...value is copied" and "final var value is guaranteed to stay the same".
I was over thinking the issue.
 
reply
    Bookmark Topic Watch Topic
  • New Topic