Case: static binding? dynamic linking?

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

So, is static binding performed in the following example to determine which sort() method to call?

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

+6
source share
2 answers

Here, as you suspected, there are two phases of binding.

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

Then, at runtime, since p really contains an instance of Child , it will be called, and you will get "Child#sort(Collection c) is invoked" .

+4
source

during compilation, static binding defines the method with which the signature will be used (collection vs hashset). at run time, the VM determines which object the method will be called on

+4
source

Source: https://habr.com/ru/post/989849/


All Articles