this 在 Java 中是一個隱含參數,代表「正在呼叫該方法的那個物件」。編譯器在背後自動將其傳入每個實例方法。
class Banana {
void f(int i) { /* 方法本體 */ }
}
Banana a = new Banana();
Banana b = new Banana();
a.f(1);
b.f(2);
呼叫 a.f(1) 時,編譯器實際轉換為 Banana.f(a, 1);呼叫 b.f(2) 則轉為 Banana.f(b, 2)。this 即為第一個隱含參數,指向當前物件(a 或 b)。
無論哪個物件呼叫方法,JVM 都會生成一個指向該物件的 this 引用。在方法內部若需取得當前物件引用,即使用 this。
public class Leaf {
private int i = 0;
Leaf increment() {
i++;
return this; // 回傳當前物件引用
}
void print() {
System.out.println("i=" + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print(); // 輸出 i=3
}
}
Leaf x:宣告引用變數 x。new Leaf():在堆積區建立 Leaf 物件。x = new Leaf():建立引用與物件的關聯。x.increment():物件呼叫方法,this 指向該物件(等同 x)。return this:回傳指向同一物件的引用,支援鏈式呼叫。此模式廣泛應用於 Builder 模式、流式 API 設計中。