0
我想做一些多態性練習,我無法弄清楚這種多態性是如何工作的。我沒有找到關於這種行使的深層信息。我希望你們能給我一些解釋。java多態性後期綁定規則
練習1:
class Top {
public void m(Middle p) System.out.print("A ");
}
class Middle extends Top {
public void m(Object p) System.out.print("M ");
public void m(Middle p) System.out.print("L ");
}
class Bottom extends Middle {
public void m(Object p) System.out.print("V ");
public void m(Middle p) System.out.print("X ");
}
class Test {
public static void run() {
Top tm = new Middle();
Middle mb = new Bottom();
tm.m (mb); -> L
tm.m(new Bottom()); -> L why?
mb.m(mb); -> X
mb.m(tm); -> V why?
mb.m(new Middle()); -> X
new Bottom().m(tm); -> V
}
}
練習2:
class Top {
public void gg(Top o) System.out.print("A ");
public void gg(Middle m) System.out.print("B ");
}
class Middle extends Top {
public void gg(Top o) System.out.print("L ");
public void gg(Bottom b) System.out.print("M ");
}
class Bottom extends Middle {
public void gg(Top o) System.out.print("X ");
public void gg(Middle m) System.out.print("Z ");
}
class Test {
public static void run() {
Top oo = new Top();
Top ff = new Middle();
Bottom uu = new Bottom();
oo.gg(ff); -> A
oo.gg(uu); -> A why?
ff.gg(ff); -> L
ff.gg(uu); -> B why?
uu.gg(ff); -> X
uu.gg(uu); -> X why?
}
}
預先感謝您!
電賀
參見https://stackoverflow.com/questions/1572322/overloaded-method-selection-based-on-the-parameters-real-type和https://stackoverflow.com/questions/14676395/ java-overloading-method-selection – DNA 2015-03-02 12:05:34
練習2的一些答案是錯誤的,如果你實際運行代碼,這可能解釋了你的難度。請參閱下面的答案。 – DNA 2015-03-02 12:26:33