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

類似的,宣告為 abstract 的方法不需要實作,其後直接加分號,如
abstract void speak(); |
繼承的子類別必須實作 abstract 方法。
舉例如下
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 | 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(); } } /* 《程式語言教學誌》的範例程式 檔名: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
沒有留言:
張貼留言