class D extends B{}
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 A
System.out.println(a2.show(c)); // ⑤ B and A
System.out.println(a2.show(d)); // ⑥ A and D
System.out.println(b.show(b)); // ⑦ B and B
System.out.println(b.show(c)); //⑧ B and B
System.out.println(b.show(d)); // ⑨ A and D
}
输出结果:
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
分析:
a1对象里面有两个方法
public String show(D obj){
return ("A and D");
}
public String show(A obj){
return ("A and A");
}
传 b时会进行向上转型走show(A obj),所以return ("A and A");
传c时也会进行向上转型到b,再向上到a走show(A obj),所以return ("A and A");
传d时直接走show(D obj),所以 return ("A and D");
a2对象里面有两个方法
public String show(D obj){
return ("A and D");
}
public String show(A obj){
return ("B and A");
}
传 b时会进行向上转型走show(A obj),所以return ("B and A");
传c时也会进行向上转型到b,再向上到a走show(A obj),所以return ("B and A");
传d时直接走show(D obj),所以 return ("A and D");
b里面三个方法
public String show(B obj){
return ("B and B");
}
public String show(A obj){
return ("B and A");
}
public String show(D obj){
return ("A and D");
}
传 b时直接走show(B obj),所以