我是一只勤奋的小菜鸟 2015-06-02 05:41 采纳率: 100%
浏览 2618
已采纳

Java新手看多态时遇到这个问题,谁能给解释下

package test;

public class test{
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{}

  • 写回答

11条回答 默认 最新

  • zjg448281779 2015-06-02 06:38
    关注

    System.out.println(a1.show(b));
    a1是A类型A对象
    所以看参数
    打印A and A
    System.out.println(a1.show(c));
    a1是A类型A对象
    所以看参数
    打印A and A
    System.out.println(a1.show(d));
    a1是A类型A对象
    所以看参数
    打印A and D
    System.out.println(a2.show(b));
    a2是A类型B对象
    所以a2.show(b)是调用A类的方法,但是B类重写了这个方法
    所以调用的是B类的方法
    public String show(A obj){
    return ("B and A");
    }
    打印B and A

    System.out.println(a2.show(c));
    a2是A类型B对象
    所以a2.show(b)是调用A类的方法,但是B类重写了这个方法
    所以调用的是B类的方法
    public String show(A obj){
    return ("B and A");
    }
    打印B and A
    System.out.println(a2.show(d));
    a2是A类型B对象
    所以a2.show(b)是调用A类的方法,
    B类没有重写该方法
    打印A and D
    System.out.println(b.show(b));
    b是B类型B对象
    调用B方法看参数
    参数遵循就近原则
    打印B and B

    System.out.println(b.show(c));
    b是B类型B对象
    调用B方法看参数
    参数遵循就近原则
    打印B and B

    System.out.println(b.show(d));

    b是B类型B对象
    调用B方法看参数
    D继承A
    调用父类的方法
    打印A and D

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(10条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog