
建構子的名稱必須和類別 (class) 名稱相同,後面接小括弧,類似方法 (method) ,可以提供參數 (parameter) 但沒有回傳值 (return value) ,參數可作為設定屬性 (field) 之用。
例如,類別 Demo 的建構子為 Demo()
class Demo { public Demo() { //相關程式碼 } //相關程式碼 } |
建構子也可以多載,另外設計類別若是沒有提供建構子,編譯器會自動提供沒有參數的建構子版本。這裡須留意,只有在沒有提供建構子的類別,編譯器才會主動提供,若是設計類別有提供任何參數版本的建構子,編譯器就不會提供沒有參數的版本。
以下程式示範 Animal 類別使用三個版本的建構子
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 | 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) { setAge( 3 ); setWeight(w); System.out.println( "使用一個參數的建構子,Animal物件已建立...." ); } public Animal() { setAge( 3 ); setWeight( 15 ); System.out.println( "使用沒有參數的建構子,Animal物件已建立...." ); } 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 JungleDemo3 { public static void main(String[] args) { Animal puppy1 = new Animal( 6 , 70 ); puppy1.speak(); Animal puppy2 = new Animal( 142 ); puppy2.speak(); Animal puppy3 = new Animal(); puppy3.speak(); } } /* 《程式語言教學誌》的範例程式 檔名:JungleDemo3.java 功能:示範物件導向的基本觀念 作者:張凱慶 時間:西元 2010 年 10 月 */ |
編譯後執行,結果如下

有三個版本的建構子,實際上我們只需保留最多參數版本的建構子,其他建構子可以利用關鍵字 this 進行呼叫,如
11 12 13 14 15 16 17 18 19 20 21 | public Animal( int w) { setAge( 3 ); setWeight(w); System.out.println( "使用一個參數的建構子,Animal物件已建立...." ); } public Animal() { setAge( 3 ); setWeight( 15 ); System.out.println( "使用沒有參數的建構子,Animal物件已建立...." ); } |
可以改成
11 12 13 14 15 16 17 | public Animal( int w) { this ( 3 , w); } public Animal() { this ( 3 , 15 ); } |
重新編譯執行,結果如下

如果需要使用 this ,必須放在建構子定義中的第一行。
中英文術語對照 | |
---|---|
建構子 | constructor |
類別 | class |
方法 | method |
參數 | parameter |
回傳值 | return value |
屬性 | field |
參考資料
http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html
http://java.sun.com/docs/books/jls/third_edition/html/classes.html
http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html
http://java.sun.com/docs/books/jls/third_edition/html/classes.html
沒有留言:
張貼留言