this 是 Java 初學者常感困惑的關鍵字。本質上,this 代表 「正在呼叫當前方法的那個物件實例的參考」,由編譯器在非靜態方法呼叫時隱式傳遞。
對於 a.f(1),編譯器實際生成類似 Banana.f(a, 1) 的調用,a 即為方法內部的 this。同理 b.f(2) 內部 this 指向 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
}
}
每次 increment() 呼叫時,this 指向同一個 x 物件,返回 this 使鏈式調用成為可能。若返回 new Leaf() 則會建立新物件,打破鏈式語意。
this 僅存在於非靜態方法/建構子中。this(...) 呼叫同類其他建構子。OuterClass.this 訪問外部類實例。