case: static binding? dynamic binding?
Asked Answered
S

2

6

I know that overloading uses static binding and overriding uses dynamic binding. But what if they are mixed? According to this tutorial, to resolve method calls, static binding uses type information while dynamic binding uses actual Object information.

So, does static binding happens in the following example to determine which sort() method to invoke?

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: The output is : Child#sort(Collection c) is invoked

Serb answered 27/6, 2015 at 6:48 Comment(0)
E
4

There are two phases of binding here, as you suspected.

First, the static phase, that will choose to call sort(Collection c). This is done in compile time, and since c is a reference of the Collection type, this method will be used, regardless of the runtime type (which is a HashSet).

Then, in runtime, since p actually contains a Child instance, it's method will be invoked, and you'll get "Child#sort(Collection c) is invoked".

Eliseoelish answered 27/6, 2015 at 7:24 Comment(0)
G
4

during compile time, static binding determines method with which signature will be used (collection vs hashset). during execution, VM determines on which object the method will be invoked

Galloon answered 27/6, 2015 at 7:22 Comment(0)
E
4

There are two phases of binding here, as you suspected.

First, the static phase, that will choose to call sort(Collection c). This is done in compile time, and since c is a reference of the Collection type, this method will be used, regardless of the runtime type (which is a HashSet).

Then, in runtime, since p actually contains a Child instance, it's method will be invoked, and you'll get "Child#sort(Collection c) is invoked".

Eliseoelish answered 27/6, 2015 at 7:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.