6

オーバーロードは静的バインディングを使用し、オーバーライドは動的バインディングを使用することを知っています。しかし、それらが混在している場合はどうなりますか?このチュートリアルによると、メソッド呼び出しを解決するために、静的バインディングは型情報を使用し、動的バインディングは実際のオブジェクト情報を使用します。

sort()では、次の例では、どのメソッドを呼び出すかを決定するために静的バインディングが行われているのでしょうか?

public class TestStaticAndDynamicBinding {
    
    @SuppressWarnings("rawtypes")
    public static void main(String[] args) {
        Parent p = new Child();
        Collection c = new HashSet();

        p.sort(c);
    }
}

.

public class Parent {
    
    public void sort(Collection c) {
        System.out.println("Parent#sort(Collection c) is invoked");
    }
    
    public void sort(HashSet c) {
        System.out.println("Parent#sort(HashSet c) is invoked");
    }
}

.

public class Child extends Parent {
    
    public void sort(Collection c) {
        System.out.println("Child#sort(Collection c) is invoked");
    }
    
    public void sort(HashSet c) {
        System.out.println("Child#sort(HashSet c) is invoked");
    }
}

ps: 出力は次のとおりです。 Child#sort(Collection c) is invoked

4

2 に答える 2

4

コンパイル時に、スタティック バインディングは、署名が使用される方法 (コレクションとハッシュセット) を決定します。実行中に、VM はメソッドが呼び出されるオブジェクトを決定します。

于 2015-06-27T07:22:11.387 に答える
4

ご想像のとおり、バインディングには 2 つのフェーズがあります。

まず、呼び出しを選択する静的フェーズsort(Collection c)です。これはコンパイル時に行われ、は型cの参照であるためCollection、実行時の型 ( ) に関係なく、このメソッドが使用されますHashSet

次に、実行時に、p実際にはChildインスタンスが含まれているため、そのメソッドが呼び出され、 が取得されます"Child#sort(Collection c) is invoked"

于 2015-06-27T07:24:08.913 に答える