this 是非靜態方法隱含參數,指向呼叫該方法的當前物件實例。編譯器在每個實例方法簽名中隱含加入 ThisType this。
public class User {
private String name; // 成員變數
public void setName(String name) { // 參數 name 遮蔽成員 name
this.name = name; // this.name 明確指向成員
}
}
public class Point {
int x, y;
String label;
public Point(int x, int y) {
this(x, y, "default"); // 呼叫另一個建構子,必須在第一行
}
public Point(int x, int y, String label) {
this.x = x;
this.y = y;
this.label = label;
}
}
public class EventSource {
public void register(Listener l) {
l.onEvent(this); // 將自己傳給監聽器
}
}
public class Outer {
private int value = 10;
class Inner {
private int value = 20;
void print() {
int value = 30;
System.out.println(value); // 30 (區域)
System.out.println(this.value); // 20 (Inner 實例)
System.out.println(Outer.this.value); // 10 (Outer 實例) ← 關鍵語法
}
}
}
this → 內部類實例。Outer.this → 外部類實例 (隱含外部類引用)。| 誤區 | 正確認知 |
|---|---|
| this 是變數 | this 是唯讀參考,不能賦值 this = null |
| 靜態方法可用 this | 靜態方法無 this,無當前實例 |
| this == 當前類 | this 是實例,非 Class 物件 |
更多範例請見:Java this 關鍵字詳細講解