my dog learned polymorphism
The moose likes Java in General and the fly likes Local Inner Class vs. final variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Local Inner Class vs. final variable" Watch "Local Inner Class vs. final variable" New topic

Local Inner Class vs. final variable

Choopong Songcharoenkij

Joined: Sep 28, 2004
Posts: 18
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.

SCEA5.0 (In Progress), SCBCD5.0, SCBCD1.3, SCWCD5.0, SCWCD1.4, SCJD, SCJP6.0, SCJP5.0, SCJP1.4, SCJA1.0<br />OMG Certified UML 2.0 Professional - Fundamental - Intermediate - Advanced <br />Oracle Database 10g Administrator Certified Associate
Emilia Ipate

Joined: Aug 09, 2005
Posts: 7
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

Joined: May 18, 2005
Posts: 84
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.

I'm a Hood Ornament
I agree. Here's the link:
subject: Local Inner Class vs. final variable
jQuery in Action, 3rd edition