OuterClass.this 表示內部類實例所關聯的外部類實例引用。
OuterClass.this.field 訪問外部類成員。OuterClass.this 而非 this(後者指內部類實例)。OuterClass outer = new OuterClass(); OuterClass.Inner inner = outer.new Inner(); 內部實例隱式持有 outer 引用,即 OuterClass.this。public class Outer {
private String name = "Outer";
class Inner {
private String name = "Inner";
void print() {
System.out.println(this.name); // Inner
System.out.println(Outer.this.name); // Outer
}
}
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.print();
}
}
非靜態內部類編譯後構造方法會隱式增加 Outer outer 參數,內部實例持有 this$0 引用指向外部實例。Outer.this 即訪問該隱式字段。
static class Inner)無 Outer.this,因不依賴外部實例。new Runnable() { void run() { System.out.println(Outer.this.name); } }。