Static vs Dynamic Binding in Java

Java 8Object Oriented ProgrammingProgramming

In Java static binding refers to the execution of a program where type of object is determined/known at compile time i.e when compiler executes the code it know the type of object or class to which object belongs.While in case of dynamic binding the type of object is determined at runtime.

Also static binding uses type of class to bind while dynamic binding uses type of object as the resolution happens only at runtime because object only created during runtime due to which dynamic binding becomes slower than in case of static binding.

As private,final and static modifiers binds to the class level so methods and variables uses static binding and bonded by compiler while the other methods are bonded during runtime based upon runtime object.

In general we can say that overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding.

Example

Live Demo

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
public class StaticDynamicBinding {
   public static void main(String[] args) {
      Collection<String> col = new HashSet<>();
      col.add("hello");
      StaticDynamicBinding sdObj = new StaticDynamicBinding();
      sdObj.print(col);
      StaticDynamicBinding sdObj1 = new StaticDynamicBindingClass();
      sdObj1.print(col);
   }
   void print(Collection<String> col) {
      System.out.println("in collection method");
   }
   void print(HashSet<String> hs) {
      System.out.println("in hashset method");
   }
}
class StaticDynamicBindingClass extends StaticDynamicBinding {
   void print(Collection<String> col) {
      System.out.println("in collection method of child class");
   }
}

Output

in collection method
in collection method of child class
raja
Published on 04-Dec-2018 12:45:10
Advertisements