Java中this的用法及在構造器中呼叫構造器
阿新 • • 發佈:2019-02-18
package object; public class E08_StaticTest { int petalCount = 0; String s = "initial value"; //(1) E08_StaticTest(int petals) { petalCount = petals; System.out.println("Constructor w/ int arg only, petalCount= " + petalCount); } //(2) E08_StaticTest(String ss) { System.out.println("Constructor w/ String arg only, s = " + ss); s = ss; } //(3) E08_StaticTest(String s, int petals) { this(petals); //! this(s); // Can't call two! this.s = s; // Another use of "this" System.out.println("String & int args"); } //(4) E08_StaticTest() { this("hi", 47); System.out.println("default constructor (no args)"); } void printPetalCount() { //! this(11); // Not inside non-constructor! System.out.println("petalCount = " + petalCount + " s = "+ s); } public static void main(String[] args) { E08_StaticTest x = new E08_StaticTest(); x.printPetalCount(); } } /* Output: Constructor w/ int arg only, petalCount= 47 String & int args default constructor (no args) petalCount = 47 s = hi *///:~
注意:this本身表示對當前物件的引用。
剛開始看這段程式碼時,沒怎麼看明白,本以為會直接輸出最後兩行,沒搞懂Constructor w/ int arg only, petalCount= 47;String & int args這兩行為什麼會輸出。後來才明白其原因,
其執行順序為: E08_StaticTest x = new E08_StaticTest();其後執行(4)的this語句->(3)的this語句->(1)確認int型別為47,輸出print->(3)的剩下語句->(4)的剩下語句。這樣輸出結果就和程式設計的一一對應了。原因:如果構造器的第一個語句形如this(...)這個構造器將呼叫同一個類的另一個構造器。