Static and Dynamic Binding
Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve 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 the 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 to bind.
Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime. Here is an example that will help you to understand both static and dynamic binding in Java.
Static binding example
public class StaticBindingTest {
public static void main(String args[]) {
Collection c = new HashSet();
StaticBindingTest et = new StaticBindingTest();
et.sort(c);
}
//overloaded method takes Collection argument
public Collection sort(Collection c) {
System.out.println("Inside Collection sort method");
return c;
}
//another overloaded method which takes HashSet argument which is sub class
public Collection sort(HashSet hs) {
System.out.println("Inside HashSet sort method");
return hs;
}
}Method overloading (same name but not parameters) is determined at compile time. The compiler decides, based on the compile time type of the parameters passed to a method call, which method having the given name should be invoked. Hence the static binding.
Dynamic binding example
public class DynamicBindingTest {
public static void main(String args[]) {
Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
vehicle.start(); //Car's start called because start() is overridden method
}
}
class Vehicle {
public void start() {
System.out.println("Inside start method of Vehicle");
}
}
class Car extends Vehicle {
@Override
public void start() {
System.out.println("Inside start method of Car");
}
}Method overriding (same name and parameters with subclass) is determined by the runtime type of an object. At runtime, the method that gets executed can be a method of some sub-class that wasn’t even written when the code that makes the call was compiled. Hence the dynamic binding.