2013年8月5日 星期一

【JAVA】建構子呼叫另一個建構子 A constructor wants to call another constructor in JAVA

相信大家對 class 裡的建構子(Constructor)並不陌生

而對於利用傳入不同格式或不同數目的參數

來達成多重建構子定義 (Constructor Overloading) 應該也沒問題

那如果今天想要在一個建構子中, 呼叫另外一個建構子呢?

假設 class 叫做 Animal()

語法就像下列這樣這麼簡單:

Animal(int foot) {
    

    Animal();     //不能使用 A
nimal(), 要用 this()

    this();

    this.foot = 2;

    this();          //一定要在這個建構子的一開始就呼叫
}





簡單的範例讓大家理解:

constructor_call_another_constructor

大家可以參考一下, 有問題也請大家不吝指教, 謝謝 :)

1 則留言: