下面的代碼相信很多人都看過,但是很多人并不知道具體的原理。。。所以把我的理解記錄下來,供大家參考。。 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{}
class E
{
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)); //① System.out.println(a1.show(c)); //② System.out.println(a1.show(d)); //③ System.out.println(a2.show(b)); //④ System.out.println(a2.show(c)); //⑤ System.out.println(a2.show(d)); // ⑥ System.out.println(b.show(b)); //⑦ System.out.println(b.show(c)); //⑧ System.out.println(b.show(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是一個A類對象,當調用a1.show(b)方法時,我們發現A類中沒有對應的方法,這時我們應該到A類的父類中去找這個方法,但是A類沒有父類,所以我們轉向括號內對象,因為B是繼承自A,可以將b看做A對象,所以這時可以調用a1.show(a)方法,打印出"A and A",同理,a1.show(c)也是打印出"A and A",對于a1.show(d),A中存在對象為D的show方法,所以直接調用,打印出"A and D"。b和a2大致相同,只是b所屬的類含有show(B b)方法。按照this.show(o)->super(this).show(o)->this.(super(o))->super.this.(super(o))的順序來進行多態調用方法的排序新聞熱點
疑難解答