电竞比分网-中国电竞赛事及体育赛事平台

分享

一道多態(tài)性的題,實(shí)在理解不了了~~~~

 ShangShujie 2006-11-19
寫出以下代碼的輸出結(jié)果
class A{
 public String f(D obj){return ("A and D");}
 public String f(A obj){return ("A and A");}
}
class B extends A{
 public String f(B obj){return ("B and B");}
 public String f(A obj){return ("B and A");}
}
class C extends B{}
class D extends B{}
class test{
 A a1 = new A();
 A a2 = new B();
 B b = new B();
 C c = new C();
 D d = new D();
 System.out.println(a1.f(b));   A and A
 System.out.println(a1.f(c));   A and A
 System.out.println(a1.f(d));   A and D
 System.out.println(a2.f(b));   B and A
 System.out.println(a2.f(c));   B and A
 System.out.println(a2.f(d));   A and D
 System.out.println(b.f(b));    B and B
 System.out.println(b.f(c));    B and B
 System.out.println(b.f(d));   A and D
}
旁邊的是標(biāo)準(zhǔn)答案,前三個都很好理解,但是后面三個真的是一頭霧水啊,難道b,c都變成類A了?還有d,是不是如果子類里沒有他的方法可調(diào)用,就看超類里是否有與他相對應(yīng)的方法?
然后最后一個,b不是已經(jīng)聲明為B類了嗎?為什么會調(diào)用A類里的方法呢?為什么結(jié)果不能是B and B呢?
大家能幫忙給小弟解解惑嗎?真是一頭霧水啊!~~~~~~~~~~~

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多