Thursday, June 21, 2007

Final Variables and Anonymous Inner Classes

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.


1 comment:

  1. NovaX4:36 AM

    Actually, the required use of final is considered a mistake. This was discussed by Bloch in "ava Puzzlers".

    If I remember correctly, the reason stated was that a C++ developer added anonomous classes and was concerned about the performance of objects on the heap. If final, they could be placed on the stack. There is no technical reason why /final/ had to be used, nor did it improve performance.

    I believe that the CICE proposal for closures would eliminate the /final/ requirement.