• Post Reply Bookmark Topic Watch Topic
  • New Topic

why method-local inner class object cannot acess local non final variable while it can access local  RSS feed

 
phooton misra
Ranch Hand
Posts: 52
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Please suggest.

why method-local inner class object cannot acess local non final variable while it can access local final variable?

thanks,

 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
phooton misra wrote:
why method-local inner class object cannot acess local non final variable while it can access local final variable?


In my opinion, you are asking the wrong question. The question should be "why inner class objects are allowed to access any local variable, final or otherwise"? The scope of local variables and the scope of instances of classes are different, so access should not be allowed at all.


Anyway, to answer your question... The JLS allows it because it may be useful. If the local variable is final, and it has already been assigned -- It is considered a constant, and the value is known, so a copy of the value is made. The inner class actually uses a copy of the variable -- and doesn't access the variable (after it has been instantiated).

Henry
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you don't mark the local variable final, the javac tool cannot check whether it has been reassigned. If it has been reassigned, then there would be a risk of the local variable and the copy in the object being different.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!