首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

徹底搞懂 Java this 關鍵字:原理、陷阱與實戰技巧

     編輯:Java 程式設計入門

this 的本質:編譯器暗中傳遞的「當前物件引用」

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)。

通俗理解:誰呼叫,this 就指向誰

無論哪個物件呼叫方法,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
    }
}

執行流程解析

  1. Leaf x:宣告引用變數 x。
  2. new Leaf():在堆積區建立 Leaf 物件。
  3. x = new Leaf():建立引用與物件的關聯。
  4. x.increment():物件呼叫方法,this 指向該物件(等同 x)。
  5. return this:回傳指向同一物件的引用,支援鏈式呼叫。

此模式廣泛應用於 Builder 模式、流式 API 設計中。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved