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

第 54 行到第 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 行
super(a, w);
這是藉由 Animal 的建構子設定 Animal 的 private 屬性 age 及 weight 的值,接著第 56 行才進行 Elephant 屬性 name 的設定。
注意第 61 行及第 65 行
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能不能只引用局部...
感謝您。
張貼留言