舉例如下
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();
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:PolymorphismDemo.java
功能:示範物件導向的基本觀念
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

留意第 87 行到第 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 |
沒有留言:
張貼留言