1、
/*
多態練習:貓狗案例
*/
1 class Animal { 2 public void eat(){ 3 System.out.println("吃飯"); 4 } 5 } 6 7 class Dog extends Animal { 8 public void eat() { 9 System.out.println("狗吃肉"); 10 } 11 12 public void lookDoor() { 13 System.out.println("狗看門"); 14 } 15 } 16 17 class Cat extends Animal { 18 public void eat() { 19 System.out.println("貓吃魚"); 20 } 21 22 public void playGame() { 23 System.out.println("貓捉迷藏"); 24 } 25 } 26 27 class DuoTaiTest { 28 public static void main(String[] args) { 29 //定義為狗 30 Animal a = new Dog(); 31 a.eat(); 32 System.out.println("--------------"); 33 //還原成狗 34 Dog d = (Dog)a; 35 d.eat(); 36 d.lookDoor(); 37 System.out.println("--------------"); 38 //變成貓 39 a = new Cat(); 40 a.eat(); 41 System.out.println("--------------"); 42 //還原成貓 43 Cat c = (Cat)a; 44 c.eat(); 45 c.playGame(); 46 System.out.println("--------------"); 47 48 //演示錯誤的內容 49 //Dog dd = new Animal(); 50 //Dog ddd = new Cat(); 51 //ClassCastException 52 //Dog dd = (Dog)a; 53 } 54 }
2、不同地方飲食文化不同的案例
1 class Person { 2 public void eat() { 3 System.out.println("吃飯"); 4 } 5 } 6 7 class SouthPerson extends Person { 8 public void eat() { 9 System.out.println("炒菜,吃米飯"); 10 } 11 12 public void jingShang() { 13 System.out.println("經商"); 14 } 15 } 16 17 class NorthPerson extends Person { 18 public void eat() { 19 System.out.println("燉菜,吃饅頭"); 20 } 21 22 public void yanJiu() { 23 System.out.println("研究"); 24 } 25 } 26 27 class DuoTaiTest2 { 28 public static void main(String[] args) { 29 //測試 30 //南方人 31 Person p = new SouthPerson(); 32 p.eat(); 33 System.out.println("-------------"); 34 SouthPerson sp = (SouthPerson)p; 35 sp.eat(); 36 sp.jingShang(); 37 System.out.println("-------------"); 38 39 //北方人 40 p = new NorthPerson(); 41 p.eat(); 42 System.out.println("-------------"); 43 NorthPerson np = (NorthPerson)p; 44 np.eat(); 45 np.yanJiu(); 46 } 47 }
題目:
1、看程序寫結果:先判斷有沒有問題,如果沒有,寫出結果
1 class Fu { 2 public void show() { 3 System.out.println("fu show"); 4 } 5 } 6 7 class Zi extends Fu { 8 public void show() { 9 System.out.println("zi show"); 10 } 11 12 public void method() { 13 System.out.println("zi method"); 14 } 15 } 16 17 class DuoTaiTest3 { 18 public static void main(String[] args) { 19 Fu f = new Zi(); 20 f.method(); 21 f.show(); 22 } 23 }
答案是: 出錯,f.method()這里出錯,父類沒有這個方法
2、看程序寫結果:先判斷有沒有問題,如果沒有,寫出結果
1 class A { 2 public void show() { 3 show2(); 4 } 5 public void show2() { 6 System.out.println("我"); 7 } 8 } 9 class B extends A { 10 public void show2() { 11 System.out.println("愛"); 12 } 13 } 14 class C extends B { 15 public void show() { 16 super.show(); 17 } 18 public void show2() { 19 System.out.println("你"); 20 } 21 } 22 public class DuoTaiTest4 { 23 public static void main(String[] args) { 24 A a = new B(); 25 a.show(); 26 27 B b = new C(); 28 b.show(); 29 } 30 }
//答案是 愛你 。
public void show() {
show2();
} 默認在B類的show2前面
多態的成員訪問特點:
方法:編譯看左邊,運行看右邊。
繼承的時候:
子類中有和父類中一樣的方法,叫重寫。
子類中沒有父親中出現過的方法,方法就被繼承過來了。