java中this關鍵字主要是用在類的成員方法中,用來指代本類所指的一個對象,注意是指代一個對象,所以this不能在靜態方法中使用(因爲靜態方法是在類加載的時候出現的,但是對象是在類加載之後的實例化出現的,可以理解爲靜態方法在this出現之前就已經存在,所以不能調用)。
- this調用成員變量
我們現在舉個例子來說明,一個箱子Box裏面可以裝兩個球(str1和str2),現在已經有了一個足球,但是我們現在給這個箱子的屬性裏添加一個動作(成員方法change),可以把裏面本來的球1換成指定的另外一個球。
class Box {
String str1 = "足球";
String str2;
void change (String str1) {
this.str1 = str1; //this調用成員變量
System.out.println("換成"+str1);
}
}
public class Main {
public static void main(String[] args) {
Box box = new Box();
System.out.println("箱子裏有"+box.str1);
box.change("籃球");
System.out.println("箱子裏有"+box.str1);
}
}
這裏面的this所起到的作用就是用來區分成員變量str1和局部變量str1的,this.str1指的就是成員變量
- this調用成員方法
我們現在給這個Box多加一個動作,換掉裏面的足球同時再放一個排球,我們已經有了換足球的動作,現在可以直接加一個放排球的,然後在main函數裏面分別調用,但是我們也可以用this關鍵字直接在新方法裏面調用成員方法
class Box {
String str1 = "足球";
String str2;
void change (String str1) {
this.str1 = str1; //this調用成員變量
System.out.println("換成"+str1);
}
void changeAndInput(String str){
this.change(str);//this調用成員方法
this.str2 = "排球";
}
}
public class Main {
public static void main(String[] args) {
Box box = new Box();
System.out.println("箱子裏有"+box.str1);
box.changeAndInput("籃球");
System.out.println((box.str2 == null) ? "箱子裏有"+box.str1 : "箱子裏有"+box.str1+"和"+box.str2);
}
}
這裏面的this調用的就是剛剛說的換籃球的成員方法
- this用來互相調用構造方法
比如說我們現在只有一個Box,裏面什麼都沒有的話,我們用構造方法可以初始化Box裏面的球
class Box {
String str1;
String str2;
Box(String str1,String str2){
this.str1 = str1;
this.str2 = str2;
}
Box(){
this("籃球","足球");//this調用構造函數
}
}
public class Main {
public static void main(String[] args) {
Box box = new Box();
System.out.println((box.str2 == null) ? "箱子裏有"+box.str1 : "箱子裏有"+box.str1+"和"+box.str2);
}
}
這裏面this用來調用構造函數的用法 this(參數),需要注意的是,這種用法只能在構造方法裏面調用其他構造方法,同時必須在該方法的第一行使用。
- this直接指代本身對象
這個地方我就不舉例子了,應該很難遇到,只是我在看hashMap的源碼中間看到的發出來大家一起瞅瞅就好~
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
在代碼第二行可以看到直接用this指代了本類的對象