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...{}
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)); ⑨
答案
① A and A A引用A对象,因为B继承A,所以参数传B相当于传A
② A and A 同上
③ A and D A中有入参是D的方法,所以是直接调用,如果去掉这个方法,还是会满足A and A
④ B and A A a2 = new B()是向上转型,此时引用是父类,其没有子类的个性化方法,所以传B对象进来时,不会找子类的方法,而是找到父类的方法,如果是向下转型
如B b1=(B)a2;此时就可以调用个性化的B,此时答案就为B and B
⑤ B and A 同上
⑥ A and D 同③
⑦ B and B 子类调用,所以可以调到子类直接的方法里面
⑧ B and B C的父类是B,所以同上
⑨ A and D 子类没有找到传D的方法,就往父类上面找