출처: http://tech-read.com/2008/06/19/why-inner-class-can-access-only-final-variable/
Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren’t final then the copy of the variable in the method could change, while the copy in the local class didn’t, so they’d be out of synch.
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.
'Archive' 카테고리의 다른 글
Java에서 static method가 오버라이드 될 수 없는 이유 (0) | 2011.11.14 |
---|---|
Unit test와 functional test의 차이점 (0) | 2011.11.14 |
두가지 대표적인 프로그래밍 스타일 (0) | 2011.11.10 |
개발의 기본 흐름 (0) | 2011.11.10 |
일에 대한 만족감 (0) | 2011.11.08 |