例如
abstract class Animal {
//相關程式碼
}如果意圖建立 abstract 的物件,會發生以下的編譯錯誤

類似的,宣告為 abstract 的方法不需要實作,其後直接加分號,如
abstract void speak();
繼承的子類別必須實作 abstract 方法。
舉例如下
abstract 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 abstract void speak();
}
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 JungleDemo92 {
public static void main(String[] args) {
Elephant puppy1 = new Elephant("大象", 6, 70);
puppy1.speak();
Elephant puppy2 = new Elephant(10, 142);
puppy2.speak();
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:JungleDemo92.java
功能:示範物件導向的基本觀念
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

| 中英文術語對照 | |
|---|---|
| 類別 | class |
| 實體化 | instantiated |
| 物件 | object |
| 父類別 | superclass |
| 子類別 | subclass |
| 繼承 | inherit |
參考資料
http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
http://java.sun.com/docs/books/jls/third_edition/html/classes.html
http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
http://java.sun.com/docs/books/jls/third_edition/html/classes.html
沒有留言:
張貼留言