this 是 Java 中的一個隱式引用變量,指向當前正在調用方法/構造器的對象實例。簡單說:「誰調用,this 就代表誰」。
public class User {
private String name;
public User(String name) {
this.name = name; // this.name 為成員變量,name 為參數
}
}
this(...) 必須放首行public User() { this("default"); }
public User setAge(int age) { this.age = age; return this; }
other.doSomething(this);this 引用(佔 1 個 slot),指向堆中對象實例。this 不存儲於此。| 特性 | 說明 |
|---|---|
| 不可賦值 | this = new Obj(); 編譯報錯 |
| 靜態方法不可用 | static 方法屬於類,無當前實例,編譯報錯 |
| 內部類訪問外部 this | OuterClass.this 區分內部類自身 this |
❌ 誤以為
this是對象本身。
✅ 正確:this是引用,指向堆內存中的對象實體,佔 4/8 字節(32/64 位 JVM)。
掌握 this 的本質與作用域,是寫出健壯 Java 代碼的基石之一。