开发者社区> 问答> 正文

JAVA多态问题

public class Test1{
public static void main(String arg[]){

        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));   //A-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(A obj){
       return ("B and A");
}
public String show(B obj){
    return ("B and B");
}
}
class C extends B{
 public String show(C obj){
     return ("C and C");
  }
  public String show(B obj){
         return ("B and C");
  }
}
class D extends B{
 public String show(D obj){
     return ("D and D");
  }
  public String show(B obj){
         return ("B and D");
  }
} 

A and A
A and A
A and D
B and A
B and A
A and D
B and B
B and B
A and D
为什么第4个输出不是B and B而是 B and A明明入参就是B类

展开
收起
蛮大人123 2016-03-25 14:54:48 1798 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    如果在子类中定义某方法与其父类有相同的名称和参数,我们说该方法被重写 (Overriding)。
    类A中的方法show(A obj) 跟类B中的方法show(B obj)因为参数不同(虽然是有继承关系,但也必须是相同才行),
    所以类B中的这个方法并不是对类A中方法的重写,它们之间并没有关系。
    A a2 = new B();这样定义的a2对象,只有show(D obj)show(A obj)方法,并且类B中的show(A obj)方法对A中的show(A obj)方法重写了,我们在调用的时候,就会走类B中的show(A obj)方法,所以输出是B and A

    2019-07-17 19:14:24
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载