转自:
下面代码输出是什么?
- public class Test3 {
- public static void main(String[] args) {
- AAA a = new BBB();
- BBB b = new BBB();
- System.out.println(a.show(b));//B and A
- }
- }
- class AAA {
- public String show(D obj){
- return ("A and D");
- }
- public String show(AAA obj){
- return ("A and A");
- }
- }
- class BBB extends AAA{
- public String show(BBB obj){
- return ("B and B");
- }
- public String show(AAA obj){
- return ("B and A");
- }
- public String show(D obj){
- return ("D and A");
- }
- }
- class C extends BBB{}
- class D extends BBB{}
- AAA a = new BBB();
- BBB b = new BBB();
- System.out.println(a.show(b));//B and A
这里面 a 虽然指向一个 BBB 对象,但声明的是一个 AAA,所以 a 只能调用 AAA 中的两个方法:
- public String show(D obj)
- public String show(AAA obj)
根本访问不到 BBB 中的方法:
- public String show(BBB obj)
a 确实指向一个 BBB 对象,因为 BBB 继承自 AAA,父类 AAA 中的
- public String show(AAA obj)
被 BBB 中的
- public String show(AAA obj)
覆盖,结果就是 B and A。
虽然传入的参数 b 是 BBB 类型,但 AAA 是 BBB 的父类,参数 b 可以被 show(AAA obj) 接受。
来源: