2011年1月3日 星期一

Limitations on inner classes in methods

在某個方法中宣告 inner class, 例如

public void perform(){
  int localVar;
  MyInnerClass {
  }
}

使用這種型式的 inner class 有一個很重要的限制:
"any of the method's local variables that are referenced by the inner class must be declared final."

若有一個物件 myInnerClass 的方法中參考到 localVar 變數, 則此變數應宣告為 final (常數).

原因: 在 perform() 方法中所建立來的 MyInnerClass 物件所看到的 localVar 應是一樣的. 但每一個 MyInnerClass 物件又都是獨立的有自己的看到的 localVar. 所以這個 localVar 會被 copy 給每個 MyInnerClass 同時限制成唯讀.

Ref: Section 6.6.2 Inner Classes within methods in Learning Java, 2nd edition, O'Relly, 2002,

沒有留言: