我有这个问题涉及继承、多态、重载和覆盖。我理解所有这些术语,但不确定它们在这里是如何工作的。这是代码:
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{}
public class whatever {
public static void main(String[] args) {
A a = new B(); // note the B here
B b = new B();
C c = new C();
D d = new D();
System.out.println(a.show(a)); // B and A
System.out.println(a.show(b)); // B and A
System.out.println(a.show(c)); // B and A
System.out.println(a.show(d)); // A and D
}
}
所以这里的任务就是寻找输出。我已经有了答案,这些是我发表的评论。
我理解第一个,因为 Java 自动执行动态绑定(bind),所以 a.show() 从 B 类调用 show() 并且 a 是 A 类型所以调用 B.show(A obj)。
最后一个也是有道理的,show() 方法被重载了,因为 d 是 D 类型,所以调用了 A.show(D obj) ,它是从 A 类继承的。
另外两个我遇到了麻烦。嗯,我明白这是有道理的,因为 b 和 c 在技术上都是 A 类型对象,但为什么它与“B 和 A”一起使用而不是“B 和 B”?
最佳答案
a
的声明类型是A
。
A 只有两种方法:一种接受 A(b 和 c 都是 A 的实例),另一种接受 D(b 和 c 都不是 D 的实例)。
所以第一个方法匹配,第二个不匹配。所以第一种方法是由编译器选择的。
在B中重写了该方法,a
的具体类型为B,所以打印出“B and A”。
方法 B.show(B)
不会覆盖方法 A.show(A)
,因为它不采用与参数相同的类型。
关于Java - 当涉及到继承、多态、重载和覆盖时调用哪个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55227081/