2

在以下代码中:

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。有人可以帮忙吗?

4

1 回答 1

2

在决定调用哪个方法时,编译时间和运行时间之间存在复杂的工作分工。有关这方面的完整故事,请参阅方法调用表达式

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

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

于 2013-02-08T00:16:21.383 回答