Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final local variable question

 
Erap Estrada
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to know the logic why the variable "ai" from the code below is not visible to the inner class "Inner". Thanks!

 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Method local classes can only access local variables that are declared final.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An instance of a local class could still be reachable after the method exits and its local variables are destroyed. If local variables are final, then their values can be copied into the instance.
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Really can not understand this..
If local variables are final, then their values can be copied into the instance.

Means if the varibale is non final wont be its value be copied into instances?Will the final variable wont lost after the method finises?May be this question sounds silly ... please help!
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It might not be obvious how an instance of a local class could still be reachable after the method exits. The key is in upcasting the reference to a type that exists outside the method's scope, as illustrated here...
 
Kalpesh Jain
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The invoked methods(and their variables) goes on to the call stack.Classes once loaded, resides on the heap. Method local classes are no exception to this. Method variables survive till method itself is alive after which they are flushed from the stack. But local classes may still have their reference with other variables hence they cannot be destroyed. And thats the reason why local classes can only access final method variables so that the method lives or dies final var's value will always be the same. If at all local classes were holding non-final variables, and if anybody tries to change its value, jvm will throw exceptions as method may not be alive.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic