this關鍵字詳解
阿新 • • 發佈:2020-12-28
this關鍵字代指當前物件,可在方法中區分全域性變數和區域性變數
public class ThisTest {
private int age;
public ThisTest(){
System.out.println("我是空參");
}
public ThisTest(int age){
this.age = age;
System.out.println("我是實參");
}
}
this關鍵字除了可以區分變數,還可以在建構函式中被呼叫,減少建構函式中重複的程式碼
public class ThisTest { private int age; public ThisTest(){ System.out.println("我是空參"); } public ThisTest(int age){ //呼叫空參建構函式 this(); this.age = age; System.out.println("我是實參"); } public static void main(String[] args) { new ThisTest(12); //先列印‘我是空參',再列印'我是實參' } }
在類載入的過程中,會生成兩個方法,一個是clinit()
方法,用來初始化靜態變數;另一個是init()
方法,在new 物件的時候被呼叫,預設是空參建構函式,那麼,如果有多個建構函式,並且又面臨在建構函式中呼叫其他建構函式方法的情況,init()
方法如何生成?
還是使用ThisTest
類來驗證:
public class ThisTest { private int age; public ThisTest(){ System.out.println("我是空參"); } public ThisTest(int age){ this(); this.age = age; System.out.println("我是實參"); } public static void main(String[] args) { new ThisTest(12); } }
使用jclasslib
反編譯得到:
可見生成的位元組碼裡面有兩個init()
方法,所以可以得知,當Java前端編譯器(也就是我們經常說的編譯器)把檔案進行編譯後,會針對不同的建構函式生成不同的init()方法,聲明瞭多少個建構函式就生成多少個過載的init()方法
再看反編譯後的方法的呼叫指令:
可以看出構造方法之間的呼叫編譯過後就是生成的init()
方法的呼叫!!!