This week's book giveaway is in the NodeJS forum.
We're giving away four copies of Serverless Applications with Node.js and have Slobodan Stojanovic & Aleksandar Simovic on-line!
See this thread for details.
Win a copy of Serverless Applications with Node.js this week in the NodeJS forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Ron McLeod
  • Tim Moores
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Vijitha Kumara

Method-local inner object and final local variables  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,
I have a query regarding method-local inner objects..
I am doing OCPJP and referring Kath Sierra, Bert Bets book for the same.
It says: "The local variables aren't guaranteed to be alive as long as the method-local inner class object is, the inner class object can't use them.
Unless the local variables are marked final or are effectively final"

I haven't understood this.. just marking it final won't make the variable live longer than scope of the method. Then how this makes a difference?


 
Saloon Keeper
Posts: 9997
208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes it will. If a local variable is effectively final, Java can create a closure over the variable so that it can be used even after the method has returned. Here's an example:

When you call greetLater(), it schedules a task that will print greeting after ten seconds, and then the method returns immediately. Even though the method has finished running, the task that is run after ten seconds can still access the greeting variable that was declared in the enclosing method's local scope.

Note that the final keyword is completely optional, and just helps you to make sure that you don't modify the variable. Instead of a method-local inner class, you can also use a lambda expression:
 
Stephan van Hulst
Saloon Keeper
Posts: 9997
208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to CodeRanch!
 
You didn't tell me he was so big. Unlike this tiny ad:
global solutions you can do at home or in your backyard
https://www.kickstarter.com/projects/paulwheaton/better-world-boo
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!