Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

local inner classes

 
vini singh
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic