2012年10月10日 星期三

[Java] final in Inner Class

final in Local Inner Class
建立在 Method 中的 inner class。
Local inner class 所在的 Method 回傳值(return)後,Method 中的變數將會被銷毀,因此在 Method 中,被 Local inner class 所用到的變數會被複製一份來使用,此時,如果該變數不是 final,則複製的變數就可能因為更改而不同步,造成錯亂,因此 Local inner class 所用到的 local variables 必須標記為 final。

final in Anonymous Inner Class
匿名式 Anonymous inner class 所用到的 local variables 也必須須標記為 final,因為 Anonymous Inner Class 在實體化時,會將使用到的 local variables 直接複製並且生成為自己的 private 變數,同樣的,出現拷貝時,就會有同步的問題,因此該變數也必須被標記為 final。


* Reference
- InnerClass 的解析 @ 來喝杯JAVA咖啡 :: 痞客邦 PIXNET ::

沒有留言:

張貼留言