java8-4 多态的练习以及题目
生活随笔
收集整理的這篇文章主要介紹了
java8-4 多态的练习以及题目
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、
/*
多態練習:貓狗案例
*/
?
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、看程序寫結果:先判斷有沒有問題,如果沒有,寫出結果
答案是: ?出錯,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前面
多態的成員訪問特點:
方法:編譯看左邊,運行看右邊。
繼承的時候:
子類中有和父類中一樣的方法,叫重寫。
子類中沒有父親中出現過的方法,方法就被繼承過來了。
轉載于:https://www.cnblogs.com/LZL-student/p/5858811.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java8-4 多态的练习以及题目的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用python下载辞典
- 下一篇: 面向对象 封装 集成 特性