This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
Hi all, i'm wondering why a local inner class, that is, an inner class defined inside a method, can "see" a final variable declared within the method body? I know it can't see non-final variables because of scope issues, but why it's different with the final keyword?
This is what i feel. Method local inner classes can only be instanciated in the method in which it is declared. When a call to the method completes the local varibles that belongs to the method are lost, but since the inner class may be alive so it can access only the final variables & members
Anonymous inner classes require final variables because of the way they are implemented in Java. An anonymous inner class (AIC) uses local variables by creating a private instance field which holds a copy of the value of the local variable. The inner class isn't actually using the local variable, but a copy. It should be fairly obvious at this point that a "Bad Thing"� can happen if either the original value or the copied value changes; there will be some unexpected data synchronization problems. In order to prevent this kind of problem, Java requires you to mark local variables that will be used by the AIC as final (i.e., unchangeable). This guarantees that the inner class' copies of local variables will always match the actual values.
Joined: Jul 03, 2005
Thank you very much for the explanations!
subject: Why local inner classes CAN "see" final variables?