Search code examples
javapolymorphismoverloadingdynamic-bindingstatic-binding

case: static binding? dynamic binding?


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


Solution

  • 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".