Static Binding vs Dynamic Binding in Java (Static Polymorphism vs. Dynamic Polymorphism) - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Static Binding vs Dynamic Binding in Java (Static Polymorphism vs. Dynamic Polymorphism)

Share This
Here are a few important differences between static and dynamic binding: 
  • Static binding in Java occurs during compile time while dynamic binding occurs during runtime. 
  • private, final and static methods and variables use static binding and are bonded by compiler while virtual methods are bonded during runtime based upon runtime object. 
  • Static binding uses Type (class in Java) information for binding while dynamic binding uses object to resolve binding. 
  • Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.

Static Binding Example in Java (known as Static Polymorphism)

MyCollection.java
import java.util.Collection; import java.util.HashSet; public class MyCollection { public Collection sort(Collection c) { System.out.println("Inside Collection sort method"); return c; } public Collection sort(HashSet hs) { System.out.println("Inside HashSet sort method"); return hs; } }
StaticBindingTest.java
import java.util.Collection; import java.util.HashSet; public class StaticBindingTest { public static void main(String args[]) { Collection c = new HashSet(); MyCollection et = new MyCollection(); et.sort(c); } }
Output: Inside Collection sort method
 
By looking at above code we can see that the bytecodes are totally different because the compiler is able to differentiate between them based on the argument list and class reference. Because all of this get resolved at compile time statically that is why Method Overloading is known as Static Polymorphism or Static Binding.

Example of Dynamic Binding in Java (known as Dynamic Polymorphism)

DynamicBindingTest.java
public class DynamicBindingTest { public static void main(String args[]) { Vehicle vehicle = new Car(); vehicle.start(); } } class Vehicle { public void start() { System.out.println("Inside start method of Vehicle"); } } class Car extends Vehicle { public void start() { System.out.println("Inside start method of Car"); } }
Because all of this get resolved at runtime only and at runtime JVM gets to know which method to invoke, that is why Method Overriding is known as Dynamic Polymorphism or simply Polymorphism or Dynamic Binding.



Happy Exploring!

No comments:

Post a Comment