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 型の場合、コンパイラは、Payment 引数を期待する Store acceptPayment メソッドのみを確​​認します。これは、Payment 引数を取るメソッドの呼び出しにコミットします。

実行時にpublic void acceptPayment (Payment p)は、対象オブジェクトのクラスである FastFoodStore のメソッドのみが考慮されます。

于 2013-02-08T00:16:21.383 に答える