一道多态性的题,实在理解不了了~~~~

来源:百度文库 编辑:神马文学网 时间:2024/04/27 23:39:25
写出以下代码的输出结果
class A{
public String f(D obj){return ("A and D");}
public String f(A obj){return ("A and A");}
}
class B extends A{
public String f(B obj){return ("B and B");}
public String f(A obj){return ("B and A");}
}
class C extends B{}
class D extends B{}
class test{
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
System.out.println(a1.f(b));   A and A
System.out.println(a1.f(c));   A and A
System.out.println(a1.f(d));   A and D
System.out.println(a2.f(b));   B and A
System.out.println(a2.f(c));   B and A
System.out.println(a2.f(d));   A and D
System.out.println(b.f(b));    B and B
System.out.println(b.f(c));    B and B
System.out.println(b.f(d));   A and D
}
旁边的是标准答案,前三个都很好理解,但是后面三个真的是一头雾水啊,难道b,c都变成类A了?还有d,是不是如果子类里没有他的方法可调用,就看超类里是否有与他相对应的方法?
然后最后一个,b不是已经声明为B类了吗?为什么会调用A类里的方法呢?为什么结果不能是B and B呢?
大家能帮忙给小弟解解惑吗?真是一头雾水啊!~~~~~~~~~~~