首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android/Java 中 this 關鍵字深度解析:隱含參數、成員區分與內部類引用

     編輯:程式設計綜合問答

this 是什麼?

this 是非靜態方法隱含參數,指向呼叫該方法的當前物件實例。編譯器在每個實例方法簽名中隱含加入 ThisType this。

三大核心用法

1. 區分同名成員變數與區域變數/參數

public class User {
    private String name; // 成員變數
    
    public void setName(String name) { // 參數 name 遮蔽成員 name
        this.name = name; // this.name 明確指向成員
    }
}

2. 建構子鏈呼叫

public class Point {
    int x, y;
    String label;
    
    public Point(int x, int y) {
        this(x, y, "default"); // 呼叫另一個建構子,必須在第一行
    }
    
    public Point(int x, int y, String label) {
        this.x = x;
        this.y = y;
        this.label = label;
    }
}

3. 傳遞當前物件引用給其他方法

public class EventSource {
    public void register(Listener l) {
        l.onEvent(this); // 將自己傳給監聽器
    }
}

進階:內部類中的 this

public class Outer {
    private int value = 10;
    
    class Inner {
        private int value = 20;
        
        void print() {
            int value = 30;
            System.out.println(value);           // 30 (區域)
            System.out.println(this.value);      // 20 (Inner 實例)
            System.out.println(Outer.this.value); // 10 (Outer 實例) ← 關鍵語法
        }
    }
}
  • this → 內部類實例。
  • Outer.this → 外部類實例 (隱含外部類引用)。

常見誤區

誤區正確認知
this 是變數this 是唯讀參考,不能賦值 this = null
靜態方法可用 this靜態方法無 this,無當前實例
this == 當前類this 是實例,非 Class 物件

參考資源

更多範例請見:Java this 關鍵字詳細講解

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