this 是當前對象的引用,指向調用方法的那個對象實例。
public class Leaf {
int i = 0;
public Leaf(int i) { this.i = i; } // 區分參數與成員變量
Leaf increament() {
i++;
return this; // 返回自身引用,支持鏈式調用
}
void print() { System.out.println("i = " + i); }
public static void main(String[] args) {
Leaf leaf = new Leaf(100);
leaf.increament().increament().print(); // 輸出 102
}
}
new Leaf(100):堆創建對象,棧變量 leaf 指向它。構造器參數 i 在棧帧中,this.i = i 賦值給堆對象成員。leaf.increament():調用對象方法,this 指向該對象。i++ 修改堆中值。return this 將引用壓入棧頂臨時槽。increament():棧頂引用調用方法,再次修改同一堆對象。print():最終引用調用打印,輸出 102。this.field = param。this 實現流式 API(如 StringBuilder、構建者模式)。other.method(this)。this(...) 必須在構造器首行。this(無當前對象)。this 指向內部類實例,外部類用 Outer.this。理解 this 在堆棧交互中的角色,能寫出更清晰的構造器、鏈式 API 並避免變量遮蔽錯誤。