It's not a secret anymore!*
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "local inner classes" Watch "local inner classes" New topic
Author

local inner classes

vini singh
Greenhorn

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
Sheriff

Joined: Aug 03, 2008
Posts: 9280
    
  17

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 ]

SCJP 6
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: local inner classes
 
Similar Threads
Anonymous classes defined in a method and final var
final variables in method
Method Inner Classes &Final Variable
Is final variable i:final int i=0;on stack or heap?
Final variables