public class Outer {
private int x = 10;
class Inner {
private int x = 20;
void print() {
System.out.println("Inner x: " + x); // 20
System.out.println("Outer x: " + Outer.this.x); // 10
}
}
}
OuterClass.this 代表外部類的當前實例(非 Class 物件)。Outer.this.field、Outer.this.method()、Outer.this 傳遞外部實例引用。
public class MainActivity extends Activity {
void startService() {
Intent intent = new Intent(MainActivity.this, MyService.class);
// MainActivity.this 是 Context 實例
startService(intent);
}
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
// 匿名內部類需用 MainActivity.this 取得 Context
}
});
}
| 語法 | 代表 | 可用範圍 |
|---|---|---|
this | 當前類實例(內部類自身) | 任何非靜態方法 |
Outer.this | 外部類實例 | 非靜態內部類 |
Outer.class | 外部類 Class 物件 | 任何地方 |
「明白了,你有一個內部類... B.this.x 內部類的 A.this.x 外部類的」