1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | class Animal { private int age; private int weight; public Animal( int a, int w) { setAge(a); setWeight(w); System.out.println( "使用兩個參數的建構子,Animal物件已建立...." ); } public Animal( int w) { this ( 3 , w); } public Animal() { this ( 3 , 15 ); } public int getAge() { return age; } public void setAge( int n) { if (n < 0 ) { age = 1 ; } else { age = n; } } public int getWeight() { return weight; } public void setWeight( int n) { if (n < 0 ) { weight = 1 ; } else { weight = n; } } public void speak() { System.out.println( "哈囉,我已經" + getAge() + "歲,有" + getWeight() + "公斤重" ); } } class Elephant extends Animal { private String name; public Elephant(String n, int a, int w) { super (a, w); setName(n); System.out.println( "使用三個參數的建構子,Elephant物件已建立...." ); } public Elephant( int a, int w) { this ( "小象" , a, w); } public Elephant() { this ( "小象" , 3 , 150 ); } public String getName() { return name; } public void setName(String n) { if (n == null || n.equals( "" )) { name = "無名氏" ; } else { name = n; } } public void speak() { super .speak(); System.out.println( "我的名字是" + getName()); } } class JungleDemo7 { public static void main(String[] args) { Elephant puppy1 = new Elephant( "大象" , 6 , 70 ); puppy1.speak(); Elephant puppy2 = new Elephant( 10 , 142 ); puppy2.speak(); Elephant puppy3 = new Elephant(); puppy3.speak(); } } /* 《程式語言教學誌》的範例程式 檔名:JungleDemo7.java 功能:示範物件導向的基本觀念 作者:張凱慶 時間:西元 2010 年 10 月 */ |
編譯後執行,結果如下

第 54 行到第 66 行
54 55 56 57 58 59 60 61 62 63 64 65 66 | public Elephant(String n, int a, int w) { super (a, w); setName(n); System.out.println( "使用三個參數的建構子,Elephant物件已建立...." ); } public Elephant( int a, int w) { this ( "小象" , a, w); } public Elephant() { this ( "小象" , 3 , 150 ); } |
這裡是類別 Elephant 的建構子部份,共有三個過載 (overload) 的建構子。 Elephant 繼承自 Animal ,因此第 55 行
54 | super (a, w); |
這是藉由 Animal 的建構子設定 Animal 的 private 屬性 age 及 weight 的值,接著第 56 行才進行 Elephant 屬性 name 的設定。
注意第 61 行及第 65 行
61 | this ( "小象" , a, w); |
這是利用關鍵字 this 呼叫具有最多參數的建構子,然後由參數的建構子進行實際的物件打造工作。
建構子如須使用 super 或 this ,只能兩者擇一,並且放在建構子定義中的第一行。
中英文術語對照 | |
---|---|
建構子 | constructor |
繼承 | inherit |
子類別 | subclass |
父類別 | superclass |
過載 | overload |
參考資料
http://download.oracle.com/javase/tutorial/java/IandI/super.html
http://java.sun.com/docs/books/jls/third_edition/html/classes.html
http://download.oracle.com/javase/tutorial/java/IandI/super.html
http://java.sun.com/docs/books/jls/third_edition/html/classes.html
1 則留言:
您好,想請教這篇例子中,因為使用this呼叫建構子,導致"使用兩個參數的建構子,Animal物件已建立...."這句話一直重複,
請問有辦法改寫成仍使用this簡化程式,但使用一個參數時就列印"使用一個參數的建構子...",兩個就印"使用兩個參數的...",不重複嗎?如if else、或this能不能只引用局部...
感謝您。
張貼留言