• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Local Inner Class vs. final variable

 
Choopong Songcharoenkij
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i know that all variables accessible to any local inner classes or anonymous classes must be final but i don't know why !!! what's the appropriate reason behind this rule ?

Thanks in advance.
 
Emilia Ipate
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The situation you are referring to involves closures = Anonymous Local Classes. Local classes can only reference local variables and parameters that are declared final.
And here is the reason: An anonymous local class can use local variables because the compiler automatically gives the class a private instance field to hold a copy of each local variable the class uses. The compiler also adds hidden parameters to each constructor to initialize these automatically created private fields. Thus, a local class does not actually access local variables, but merely its own private copies of them. The only way this can work correctly is if the local variables are declared final, so that they are guaranteed not to change. With this guarantee in place, the local class is assured that its internal copies of the variables accurately reflect the actual local variables.

Hope this helps you.
 
Megs Maquito
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
security. imagine having a BankAccount class with the current interest rate not being final? Then it could be changed to 100% or probably bigger, i know i would.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic