public 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){ //重寫show(A obj)
return ("B and A");
}?
}
class C extends B{
}
class D extends B{
}
?
public class TestA {
public static void main(String[] args) {
// TODO Auto-generated method stub
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
System.out.println("1--" + a1.show(b));
System.out.println("2--" + a1.show(c));
System.out.println("3--" + a1.show(d));
System.out.println("4--" + a2.show(b));
System.out.println("5--" + a2.show(c));
System.out.println("6--" + a2.show(d));
System.out.println("7--" + b.show(b));
System.out.println("8--" + b.show(c));
System.out.println("9--" + b.show(d));?
}
}
?
輸出結果為
1--A and A
2--A and A
3--A and D
4--B and A
5--B and A
6--A and D
7--B and B
8--B and B
9--A and D
解析:
①,②,③調用a1.show()方法,a1 屬于A類,A類有兩個方法show(D obj)和show(A obj)。①a1.show(b),參數b為A類的子類對象,這里為向上轉型,相當于A obj=b;所以調用show(A obj)方法,得到A and A結果。②同理,③參數為d,調用show(D obj),得到A and D。
④,⑤,⑥調用a2.show()方法,A a2 = new B();是向上轉型,所以對a2方法的調用,使用A1類的方法show(D obj)和show(A obj),但此時show(A obj)已經被重寫為return ("B and A"), ④a2.show(b),調用show(A obj),得到B and A。⑤同理,⑥調用show(D obj),得到A and D。
⑦,⑧,⑨調用b.show()方法,b為B類,B類的show方法有繼承的show(D obj),自己的兩個show(B obj)、show(A obj)。
⑦調用show(B obj),得到B and B,⑧向上轉型,調用show(B obj),得到B and B⑨show(D obj),得到A and D