混合类型java多态。输出不是预期的

时间:2013-02-07 23:59:31

标签: java

在以下代码中:

class Payment {   }
class CashPayment extends Payment{   }

class Store{    
    public void acceptPayment (Payment p)
    {System.out.println ("Store::Payment");}

}
class FastFoodStore extends Store {
    public void acceptPayment (CashPayment c)
    {System.out.println ("FastFoodStore::CashPayment");}

    public void acceptPayment (Payment p)
    {System.out.println ("FastFoodStore::Payment");}

}

//
public class Example {  

    public static void main(String [] args){

        Store store1 = new Store();
        FastFoodStore sandwitchPlace = new FastFoodStore ();
        Store store2 = new FastFoodStore();


        Payment p1 = new Payment();
        CashPayment cp = new CashPayment();
        Payment p2 = new CashPayment();


        store1.acceptPayment (p1);
        store1.acceptPayment (cp);
        store1.acceptPayment (p2); 

        sandwitchPlace.acceptPayment (p1);
        sandwitchPlace.acceptPayment (cp);
        sandwitchPlace.acceptPayment (p2);

        store2.acceptPayment (p1);
        store2.acceptPayment (cp);
        store2.acceptPayment (p2);



    }   
}

我真正不明白的是为什么

store2.acceptPayment (cp);

会显示FastFoodStore :: Payment但不会显示FastFoodStore :: CashPayment? store2基本上会在运行时调用FastFoodStore中的方法并传递CashPayment类型参数。在这种情况下,会显示FastFoodStore :: CashPayment。 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

在决定调用哪个方法时,编译时和运行时之间存在复杂的分工。有关此内容的完整报道,请参阅Method Invocation Expressions

在您的示例中,当目标表达式是Store类型时,编译器将只看到Store acceptPayment方法,该方法需要Payment参数。那提交调用一个接受Payment参数的方法。

在运行时,只考虑FastFoodStore中的public void acceptPayment (Payment p)方法,即目标对象的类。