日期:2014-05-20  浏览次数:20754 次

一个关于多态性的小问题
有这样一段代码:

class   A{
    void   f(A   o){
        System.out.print( "1   ");
    }
}

class   B   extends   A{
    void   f(A   o){
        System.out.print( "2   ");
    }
    void   f(B   o){
        System.out.print( "3   ");
    }
   
    public   static   void   main(String   args[]){
    A   a   =   new   A();
    A   ab   =   new   B();
    B   b   =   new   B();
   
    a.f(a);
    a.f(ab);
    a.f(b);
    ab.f(a);
    ab.f(ab);
    ab.f(b);
    b.f(a);
    b.f(ab);
    b.f(b);
    }
}

为什么运行结果是1   1   1   2   2   2   2   2   3   ?

请高手指点,谢谢!

------解决方案--------------------
Two simple rules:
1, Overloaded methods are determined at compilation time based on the argument reference variable type.
2, Overridden methods are executed at runtime based on the actual instance type.

For the given program, at compilation time:
-----------------------------------------------
public static void main(String args[]){
A a = new A();
A ab = new B();
B b = new B();

a.f(a); //class A, method f(A)
a.f(ab); //class A, method f(A), ab IS-A A.
a.f(b); //class A, method f(A), b IS-A A.
ab.f(a); //class A, method f(A)
ab.f(ab); //class A, method f(A)
ab.f(b); //class A, method f(A)
b.f(a); //class B, method f(A)
b.f(ab); //class B, method f(A)
b.f(b); //class B, method f(B)
}
------------------------------------------------
At runtime:
------------------------------------------------
public static void main(String args[]){
A a = new A();
A ab = new B();
B b = new B();

a.f(a); //class A, method f(A)
a.f(ab); //class A, method f(A), ab IS-A A.
a.f(b); //class A, method f(A), b IS-A A.
ab.f(a); //class B, method f(A), overridden method f(A) from class A
ab.f(ab); //class B, method f(A), overridden method f(A) from class A
ab.f(b); //class B, method f(A), overridden method f(A) from class A
b.f(a); //class B, method f(A), overridden method f(A) from class A
b.f(ab); //class B, method f(A), overridden method f(A) from class A
b.f(b); //class B, method f(B), overloaded method in class B
}
---------------------