对多态的理解例子
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));?
}
}
?
輸出結(jié)果為
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
解析:
①,②,③調(diào)用a1.show()方法,a1 屬于A類,A類有兩個方法show(D obj)和show(A obj)。①a1.show(b),參數(shù)b為A類的子類對象,這里為向上轉(zhuǎn)型,相當于A obj=b;所以調(diào)用show(A obj)方法,得到A and A結(jié)果。②同理,③參數(shù)為d,調(diào)用show(D obj),得到A and D。
④,⑤,⑥調(diào)用a2.show()方法,A a2 = new B();是向上轉(zhuǎn)型,所以對a2方法的調(diào)用,使用A1類的方法show(D obj)和show(A obj),但此時show(A obj)已經(jīng)被重寫為return ("B and A"), ④a2.show(b),調(diào)用show(A obj),得到B and A。⑤同理,⑥調(diào)用show(D obj),得到A and D。
⑦,⑧,⑨調(diào)用b.show()方法,b為B類,B類的show方法有繼承的show(D obj),自己的兩個show(B obj)、show(A obj)。
⑦調(diào)用show(B obj),得到B and B,⑧向上轉(zhuǎn)型,調(diào)用show(B obj),得到B and B⑨show(D obj),得到A and D
轉(zhuǎn)載于:https://www.cnblogs.com/houxudong/p/7239257.html
總結(jié)
- 上一篇: 前端学习路线汇总
- 下一篇: hibernate cascade的真正