Java this 關鍵字
示例
將 this
與類屬性 (x) 一起使用
public class Main {
int x;
// Constructor with a parameter
public Main(int x) {
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
定義和用法
this
關鍵字指代方法或建構函式中的當前物件。
this
關鍵字最常見的用法是消除類屬性與同名引數(因為類屬性被方法或建構函式引數遮蔽)之間的混淆。如果省略上面示例中的關鍵字,輸出將是“0”而不是“5”。
this
還可以用於
- 呼叫當前類建構函式
- 呼叫當前類方法
- 返回當前類物件
- 在方法呼叫中傳遞引數
- 在建構函式呼叫中傳遞引數
相關頁面
在我們的Java 類/物件教程中閱讀有關物件的更多資訊。
在我們的 Java 建構函式教程中瞭解更多關於建構函式的資訊。
在我們的 Java 方法教程 中閱讀更多關於方法的資訊。