內部類方法中,OuterClass.this 即為創建該內部類實例的外部類對象引用。編譯期類型檢查,運行期零開銷。
class Sequence {
private Object[] o;
private class SSelector implements Selector {
public Object current() { return o[i]; } // 直接訪問外部 private 字段
// 等價於 Sequence.this.o[i]
}
}
非靜態內部類實例不能直接 new Outer.Inner(),必須憑藉外部實例:
Parcel11 p = new Parcel11();
Parcel11.Contents c = p.new Contents(); // 正確
Parcel11.Destination d = p.new Destination("Tanzania"); // 正確
// Parcel11.Contents c2 = new Parcel11.Contents(); // 編譯錯誤
內部類實例構造時,編譯器隱式傳入 this(外部引用)作為構造器隱藏參數。無外部實例,無法完成綁定。
static 內部類不綁定外部實例,可直接 new Outer.StaticInner()。詳見下一節。