Java關(guān)鍵字"this" 是一個(gè)引用,它指向當(dāng)前對象。
“this” 關(guān)鍵字的使用方法有以下幾種:
在構(gòu)造方法中,用于在創(chuàng)建對象時(shí)調(diào)用另一個(gè)構(gòu)造方法。這個(gè)調(diào)用必須在構(gòu)造方法的第一行。 例如:
public MyClass(int x) {
this(x, 0); // 調(diào)用另一個(gè)構(gòu)造方法
}
public MyClass(int x, int y) {
// 其他代碼
}
在實(shí)例方法中,用于引用當(dāng)前對象。通常是用于區(qū)分實(shí)例變量和方法參數(shù)之間的歧義。 例如:
public class MyClass {
private int x;
public void setX(int x) {
this.x = x; // 使用 "this" 關(guān)鍵字引用當(dāng)前對象的實(shí)例變量
}
}
在內(nèi)部類中,用于引用外部類的實(shí)例。如果內(nèi)部類和外部類具有相同的成員變量或方法名,可以通過 “this” 關(guān)鍵字引用外部類的實(shí)例。 例如:
public class OuterClass {
private int x;
public class InnerClass {
private int x;
public void printX() {
System.out.println("內(nèi)部類的 x 值:" + this.x); // 內(nèi)部類的 x 值
System.out.println("外部類的 x 值:" + OuterClass.this.x); // 外部類的 x 值
}
}
}
總之,“this” 關(guān)鍵字主要用于在構(gòu)造方法中調(diào)用另一個(gè)構(gòu)造方法、引用當(dāng)前對象的實(shí)例變量,以及在內(nèi)部類中引用外部類的實(shí)例。