首先在我們寫一個JavaBean的時候都會寫調用訪問這個類屬性的getter和setter方法或者有參的構造方法例如:
public class Employee1 {
private String name;
private int age;
private String sex;
private String post;
private double salary;
//有參構造
public Employee1(String name, int age, String sex, String post, double salary) {
super();
this.name = name;
this.age = age;
this.sex = sex;
this.post = post;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
我們可以看到裏面都用到了this這個關鍵字。它的意思是“當前對象的”下面就來看下它的三個作用:
1、用來在類的內部區分屬性和同名形參,或者說通過this關鍵字訪問對象的屬性(常用)。
上面類的name屬性的setNmae方法中,所傳形參String name和類的屬性name同名,在給屬性name賦值的時候,爲了區分屬性和形參,使用this.name來調用類的屬性,並使用形參name爲其賦值。這裏this保存的是對象的引用,即對象的虛擬地址,看下面的的代碼:
public class Hero {
String name; //姓名
float hp; //血量
float armor; //護甲
int moveSpeed; //移動速度
//打印內存中的虛擬地址
public void showAddressInMemory(){
System.out.println("打印this看到的虛擬地址:"+this);
}
public static void main(String[] args) {
Hero garen = new Hero();
garen.name = "蓋倫";
//直接打印對象,會顯示該對象在內存中的虛擬地址
//格式:Hero@c17164 c17164即虛擬地址,每次執行,得到的地址不一定一樣
System.out.println("打印對象看到的虛擬地址:"+garen);
//調用showAddressInMemory,打印該對象的this,顯示相同的虛擬地址
garen.showAddressInMemory();
Hero teemo = new Hero();
teemo.name = "提莫";
System.out.println("打印對象看到的虛擬地址:"+teemo);
teemo.showAddressInMemory();
}
}
運行結果如下,打印對象和打印this記過的都是對象的虛擬地址:
2、在需要使用當前對象時,直接使用this,比如返回當前對象:
在上面的Hero類中添加如下方法:
//增加血量
public Hero addHp(float add) {
hp=hp+add;
return this;
}
該方法用來增加血量,可以看到這個方法有返回值,返回的是Hero類的this,也就是返回了一個Hero類的一個對象,這樣做的好處是,在我們需要連掉的時候直接用返回值就可以調用,比如:對象.addHp(2.5).addHp(3.5);
3.在類的構造方法中,調用當前類的其它構造方法
如果要在一個構造方法中,調用另一個構造方法,可以使用this(),代碼如下:
public class Hero {
String name; //姓名
float hp; //血量
float armor; //護甲
int moveSpeed; //移動速度
//帶一個參數的構造方法
public Hero(String name){
System.out.println("一個參數的構造方法");
this.name = name;
}
//帶兩個參數的構造方法
public Hero(String name,float hp){
this(name);
System.out.println("兩個參數的構造方法");
this.hp = hp;
}
public static void main(String[] args) {
Hero teemo = new Hero("提莫",383);
System.out.println(teemo.name);
}
}
在上面代碼中可以看到,帶兩個參數的構造方法中通過this(),調用了帶一個參數的構造方法,如果有多個構造方法,他是通過參數的個數和類型去匹配對應的構造函數。
在有些特殊場景中會用到這中方法,比如一個類它實例化的對象有一部分屬性是相同的,name就可以在寫構造方法的時候把那部分屬性固定。
需要注意的是這種用發this(),必須放在方法的第一行。