This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes local inner classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "local inner classes" Watch "local inner classes" New topic

local inner classes

vini singh

Joined: Dec 04, 2008
Posts: 18
why local inner classes can be abstract/final.?look i know they cant be same at both the time.

why local class can acess only the final variable declared in the enclosing method and not other variables?
Ankit Garg

Joined: Aug 03, 2008
Posts: 9327

local classes are similar to normal classes, so they can be declared final or abstract.

local classes can access final constants of enclosing method as it has a local copy of them with itself. You can see my blog for more information on this. The link is in my signature...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
why local class can acess only the final variable declared in the enclosing method and not other variables?

The local variables of the method live on the stack, and exist only for the lifetime of the method. When the method ends, the stack frame is blown away and the variable is history. But even after the method completes, the inner class object created within it might still be alive on the heap if, for example, a reference to it was passed into some other code and then stored in an instance variable. Because the local variables aren't guaranteed to be alive as long as the method-local inner class object, the inner class object can't use them. Unless the local variables are marked final!

for example:

in main method:
Here you can see we can access method local final variable outside the method. And print its value. As final variable is not stored in stack so it remains outside the method. But if you have used local variable like j in this code then this variable get deleted with the stack frame, so we cannot use local variable in the local methods.

It is not like final variable scope exists outside the method, but The compiler gives the inner class a copy of the variable as it is final, it is guarantee that it will not change.

[ December 08, 2008: Message edited by: Punit Singh ]
[ December 08, 2008: Message edited by: Punit Singh ]

jQuery in Action, 2nd edition
subject: local inner classes