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{}
public class testJava{
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.f(a1));
System.out.println(a1.f(b));
System.out.println(a1.f(c));
System.out.println(a1.f(d));
System.out.println(a2.f(a1));
System.out.println(a2.f(b));
System.out.println(a2.f(c));
System.out.println(a2.f(d));
System.out.println(b.f(a1));
System.out.println(b.f(b));
System.out.println(b.f(c));
System.out.println(b.f(d));
}
}
能搞正确输出结果就可以说明掌握得差不多了 :)
A and A
A and A
A and A
A and D
B and A
//B and A
//B and A
//A and D
B and A
B and B
B and B
A and D
能给讲一下双斜线的结果是怎么回事啊,我不是很明白.....
弓雖
2007-04-18 17:15:15
A a2=new B(); 这样的话,a2被转化为A类型。所以a2具有两个方法,一个是A 的f(D),输出A and D,另一个是被覆盖的f(A)方法,输出B and A,而并不具有B的f(B)方法。因为a2只能访问A中具有的方法(包括被重载和覆盖的方法)。所以
a2.f(a1)调用f(A),输出B and A
a2.f(b),没有完全匹配的方法,将b转为父类型A,然后调用f(A)
a2.f(c),没有完全匹配的方法,将c转为父类型A,然后调用f(A)
a2.f(d), 调用f(D),输出A and D
希望这样可以说清楚吧 :)