关于一道有关'多态'的面试题
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 TestComplexPoly{
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(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
问题就是这两个为什么会是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
}
}
------解决方案--------------------这个以前不就 贴过了么?
早绑定和晚绑定
System.out.println(a2.f(b)); //B and A
System.out.println(a2.f(c)); //B and A
就相当于a2.f((A)b)
a2.f((A)c) //b,c都是a的子类
其实就是早绑定
------解决方案--------------------