这题我也做错了,大家看看吧,就当为自己以后面试碰上这种做准备了,做出正确答案的给个解释~~~
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 {
}
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 D
B and A
B and A
A and D
B and B
B and B
A and D
就说第四个吧,因为引用型变量a2中不可能有子类B,所以要调用show(A obj)方法,调用时也是多态
当然我也做错了,谢谢楼主分享