Java 程式設計 -- 物件導向中的多型機制
Java 程式簡介運算式分枝迴圈陣列函數遞迴錯誤處理物件導向封裝繼承多型技巧函式庫字串數學正規表達式容器檔案網路資料庫視窗ThreadListener錯誤陷阱相關檔案相關資源教學錄影Eclipse考題解答訊息相關網站參考文獻最新修改簡體版English |
範例程式:Zoo.javaabstract class Animal { abstract void speak(); } class Cat extends Animal { void speak() { System.out.println("喵喵!"); } } class Dog extends Animal { void speak() { System.out.println("汪汪!"); } } class Zoo { public static void main(String[] args) { Cat c1 = new Cat(); Animal[] animals = new Animal[] { new Cat(), new Dog(), new Dog(), new Cat(), new Dog() }; for (int i=0; i<animals.length; i++) { animals[i].speak(); } } } 執行結果
延伸abstract class Animal { String name=""; abstract void speak(); /* { System.out.println("未定義!"); } */ } interface Printable { void print(); } class Cat extends Animal implements Printable { public Cat() { name = "貓"; } public void speak() { System.out.println("喵喵!"); } public void print() { System.out.print(name+":"); speak(); } } class Dog extends Animal implements Printable { public Dog() { name = "狗"; } public void speak() { System.out.println("汪汪!"); } public void print() { System.out.print(name+":"); speak(); } } class Zoo { public static void main(String[] args) { // Animal a = new Animal(); // a.speak(); Cat c1 = new Cat(); System.out.println("=============c1.speak()==============="); c1.speak(); System.out.println("=============Dogs, Cats, speak()======"); Animal[] animals = new Animal[] { new Cat(), new Dog(), new Dog(), new Cat(), new Dog() }; for (int i=0; i<animals.length; i++) { animals[i].speak(); } System.out.println("=============Dogs, Cats, print()======"); Printable[] pa = new Printable[] { new Cat(), new Dog(), new Dog(), new Cat(), new Dog() }; for (int i=0; i<animals.length; i++) { pa[i].print(); } } } |
page revision: 4, last edited: 13 Oct 2011 00:29
abstract class Animal {
String name="";
abstract void speak();
/*{
System.out.println("未定義");
}*/
}
interface printable {
void print();
}
class Cat extends Animal implements printable {
public Cat() {
name = "貓";
}
public void speak() {
System.out.println("喵喵!");
}
public void print() {
System.out.print(name+":");
}
}
class Dog extends Animal implements printable{
public Dog() {
name = "狗";
}
public void speak() {
System.out.println("汪汪!");
}
public void print() {
System.out.print(name+":");
}
}
class Zoo {
public static void main(String[] args) {
// Animal a = new Animal();
// a.speak();
Cat c1 = new Cat();
System.out.println("=========c1.speak()=========");
c1.speak();
System.out.println("=========Dogs, Cats,speak()=========");
Animal[] animals = new Animal[] { new Cat(),
new Dog(), new Dog(), new Cat(), new Dog() };
for (int i=0; i<animals.length; i++) {
animals[i].speak();
}
System.out.println("=========Dogs, Cats,speak()=========");
printable[] pa = new printable[] { new Cat(),
new Dog(), new Dog(), new Cat(), new Dog() };
for (int i=0; i<animals.length; i++) {
pa[i].print();
animals[i].speak();
}
}
}
Post preview:
Close preview