多态坑题

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{}

class  DynamicTest
{   
    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));   

实际上这里涉及方法调用的优先级问题,优先级由高到低依次为:

this.show()--->super.show()-->this.show((super)0)-->super.show((super)0)


    System.out.println(a1.show(b));       A and A
    System.out.println(a1.show(c));       A and A
    System.out.println(a1.show(d));       A and D

    System.out.println(a2.show(b));       B and A                                  
    System.out.println(a2.show(c));       B and A
    System.out.println(a2.show(d));       A and D
    
    System.out.println(b.show(b));        B and B
    System.out.println(b.show(c));        B and B
    System.out.println(b.show(d));        A and D
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 很多人生病,愿意用汤滋补身体,说营养。其实汤里大多是脂肪,所以有饱腹感。 很多人愿意用海参调养身体,甚至...
    8ad130a09427阅读 1,501评论 4 1
  • 八十年代《上海滩》热播,许文强的白围巾疯魔,当时物资还算贫乏,但可以回家殃及妈妈织一条,挂在脖子上甩来甩去招摇过街...
    陈厂长阅读 3,328评论 2 1
  • 最近宅着看书,研究《思维导图》、《启动大脑》、《快速阅读》等相关的技能,形影相吊中稍感枯燥,另外也贪心的想有更多的...
    天外来客人阅读 1,709评论 0 0
  • 【武夷岩茶】您知道那么多品种武夷茶的始祖是谁吗? ——菜茶 「什么是菜茶?」 武夷山的;土生土長的;有性繁殖的;野...
    鼎典美育婷婷阅读 1,917评论 0 0