舉例如下
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 | class Animal { private int age; private int weight; public Animal( int a, int w) { setAge(a); setWeight(w); } 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); } 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() { System.out.println( "哈囉,我的名字是" + getName()); System.out.println( "我已經" + getAge() + "歲,有" + getWeight() + "公斤重" ); } } class PolymorphismDemo { public static void main(String[] args) { Animal puppy1, puppy2, puppy3; puppy1 = new Elephant( "大象" , 6 , 70 ); puppy2 = new Elephant(); puppy3 = new Elephant( "林旺" , 88 , 5000 ); puppy1.speak(); puppy2.speak(); puppy3.speak(); } } /* 《程式語言教學誌》的範例程式 檔名:PolymorphismDemo.java 功能:示範物件導向的基本觀念 作者:張凱慶 時間:西元 2010 年 10 月 */ |
編譯後執行,結果如下

留意第 87 行到第 90 行
87 88 89 90 | Animal puppy1, puppy2, puppy3; puppy1 = new Elephant( "大象" , 6 , 70 ); puppy2 = new Elephant(); puppy3 = new Elephant( "林旺" , 88 , 5000 ); |
puppy1 、 puppy2 與 puppy3 被宣告為 Animal 型態,但其後以 Elephant 型態的建構子建立物件,這個意思是說,對父類別, 也就是 Animal 型態的參考變數,實際可以由子類別,也就是 Elephant 型態來建立物件。
多型的技巧也可用在方法 (method) 的參數 (parameter) 與回傳值 (return value) 型態上。
中英文術語對照 | |
---|---|
多型 | polymorphism |
類別 | class |
繼承 | inherit |
父類別 | superclass |
子類別 | subclass |
方法 | method |
參數 | parameter |
回傳值 | return value |
沒有留言:
張貼留言