在說this之前先說下對象的創建
對象創建的過程
構個造方法是創建Java對象的重要途徑,通過new關鍵字調用構造器時,構造器也確實返回該類的對象,但這個對象並不是完全由構造器負責創建。創建一對象分爲如下四步:
1. 分對配象空間,並將對象成員變量初始化爲0或空
2. 執行屬性值的顯示初始化
3. 執行構造方法
4. 返回對象的地址給相關的變量
this的本質
this的本質就是“創建好的對象的地址”! 由於在構造方法調用前,對象已經創建。因此,在構造方法中也可以使用this代表“當前對象” 。
this最常的用法:
1. 在程序中產生二義性之處,應使用this來指明當前對象;普通方法中,this總是指向調用該方法的對象。構造方法中,this總是指向正要初始化的對象。
2. 使用this關鍵字調用重載的構造方法,避免相同的初始化代碼。但只能在構造方法中用,並且必須位於構造方法的第一句。
3. this不能用於static方法中。
/**
* 測試this關鍵字
*
* 用法一舉例說明
*
*/
public class TestThis {
int id;
String name;
int age;
public TestThis() {
}
public TestThis(int id ,String name) {
System.out.println("正在初始化已創建好的對象:"+this);
//此時的this表示相應的創建好的對象的地址;
this.id = id;//不寫this就無法區分局部變量id和成員變量id;
this.name = name;
}
public static void main(String[] args) {
TestThis t = new TestThis(1001,"anan");
System.out.println("打印anan的對象地址:"+t);
}
}
運行結果:
/**
* 測試this關鍵字
*
* 用法二舉例說明:調用重載構造方法
*
*/
public class TestThis {
int id;
String name;
int age;
public TestThis() {
}
public TestThis(int id ,String name) {
this();//調用無參的構造函數,必須位於第一行
this.id = id;//不寫this就無法區分局部變量id和成員變量id;
this.name = name;
}
public TestThis(int id,String name,int age) {
this(id,name); //調用的帶參的構造函數,並且必須位於第一行;
this.age = age;
}
void washHand(){
System.out.println("我必須先洗下手!");
}
void eat() {
this.washHand();//調用本類中的washHand;
System.out.println("可以開始吃飯啦!");
}
public static void main(String[] args) {
TestThis t = new TestThis(1001,"anan");
t.eat();
}
}
運行結果: