[BIT0429]-Java 多態中父類引用指向子類對象的經典代碼

来源:互联网 发布:笑傲江湖小说知乎 编辑:程序博客网 时间:2024/06/07 18:52

我們給出一段父類引用指向子類對象的經典代碼,以讓您分析其運行結果和更加深入了解這個原理的精妙之處:

package cn.bjsxt.oop03;public class Test1 {    public static void main(String[] args) {        A a1 = new A();          A a2 = new B();          B b = new B();          C c = new C();           D d = new D();           System.out.println(a1.show(b));           System.out.println(a1.show(c));            System.out.println(a1.show(d));           System.out.println(a2.show(b));          System.out.println(a2.show(c));          System.out.println(a2.show(d));          System.out.println(b.show(b));           System.out.println(b.show(c));            System.out.println(b.show(d));     }}class A{      public String show(D obj){             return ("A and D");      }       public String show(A obj){             return ("A and A");      }   }   class B extends A{      public String show(B obj){             return ("B and B");      }      public String show(A obj){             return ("B and A");      }   }  class C extends B{}   class D extends B{}
//這是運行結果A and AA and AA and DB and AB and AA and DB and BB and BA and D
2017/10/24 BIT创作,您可以免费转载和使用!(本模块博客是作者学习期间整理的学习心得,不是java技术的标准严格学习文档,仅作参考交流使用,对于使用本文档的后果,作者不作任何口头或书面的承诺)