给大家出个题,问一个多态的问题,大神们谁能解答?
这题我也做错了,大家看看吧,就当为自己以后面试碰上这种做准备了,做出正确答案的给个解释~~~public class PolyDemo08{--------------------编程问答-------------------- 对了,我那个注释很多是错误答案,别误导大家。。。 --------------------编程问答--------------------
public static void main(String[] args){
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));//"A and A"
System.out.println("⑵ " + a1.show(c)); //"A and A"
System.out.println("⑶ " + a1.show(d)); //"A and D"
System.out.println("⑷ " + a2.show(b)); //"B and B"
System.out.println("⑸ " + a2.show(c));//"B and B"
System.out.println("⑹ " + a2.show(d)); //"B and B"
System.out.println("⑺ " + b.show(b)); //"B and B"
System.out.println("⑻ " + b.show(c)); //"B and B"
System.out.println("⑼ " + b.show(d)); //"B and B"
}
}
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 {
}
实际上这里涉及方法调用的优先问题 ,
优先级由高到低依次为:this.show(object)、super.show(object)、 this.show((super)object)、super.show((super)object)
http://developer.51cto.com/art/200906/130414.htm --------------------编程问答--------------------
++正解 --------------------编程问答-------------------- 结果 A and A
A and A
A and D
B and A
B and A
A and D
B and B
B and B
A and D
就说第四个吧,因为引用型变量a2中不可能有子类B,所以要调用show(A obj)方法,调用时也是多态
当然我也做错了,谢谢楼主分享 --------------------编程问答-------------------- 我也错了 不知道二楼说的是不是绝对正确
补充:Java , Java SE