Java中的多态调用问题

December 15, 2016

问题:

下面代码输出是什么?

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

解答:

先说为什么不是B and B。
        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可以传入show(AAA obj)?

虽然传入的参数b是BBB类型,但AAA是BBB的父类,参数b可以被show(AAA obj)接受。