寫出以下代碼的輸出結果
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 } 旁邊的是標準答案,前三個都很好理解,但是后面三個真的是一頭霧水啊,難道b,c都變成類A了?還有d,是不是如果子類里沒有他的方法可調(diào)用,就看超類里是否有與他相對應的方法? 然后最后一個,b不是已經(jīng)聲明為B類了嗎?為什么會調(diào)用A類里的方法呢?為什么結果不能是B and B呢? 大家能幫忙給小弟解解惑嗎?真是一頭霧水啊!~~~~~~~~~~~
|
|
來自: ShangShujie > 《java》