Search This Blog

Tuesday, March 22, 2011

Tutorial : Early Binding vs Late Binding (Dynamic Binding)

Connecting a method call to method body is called as binding.

If the binding happens during the compile time then it is called early binding and if the binding happens during the run time then it is called late binding. More detailed explanation is given below

“When binding is performed before the program is run (by the compiler and linker, if there is one), it’s called early binding. You might not have heard the term before because it has never been an option with procedural languages. C compilers have only one kind of method call, and that’s early binding. The other solution is called late binding, which means that the binding occurs at run time, based on the type of object. Late binding is also called dynamic binding or run-time binding”.

The main advantage of late binding over the early binding is due the following reasons.

  1. Malleability
  2. Maintainability
  3. Extensibility

A simple example can help you understanding the concept.

class Animal{
 public void eat(){
  System.out.println("Animal Eating");
 }
}
class Dog extends Animal{
 public void eat(){
  System.out.println("Dog eating");
 } 
}
class Eating{
 public void printEat(Animal a){
  a.eat();
 }
}


In the above example we have three classes Animal,Dog and Eating. Eating class has a method by name printEat and takes Animal class as an argument. If we send an animal object to that method it prints “Animal Eating” whereas if we send Dog class it prints “Dog eating”. What happens internally is that eat method on Animal object is not linked at compile time, whereas it is linked at runtime.At runtime if the object is of type animal it prints eat method of animal, if it is of Dog type it prints eat method of dog. Later if they add a new class Cat (Cat IS-A animal) then it executes eat method of Cat. Just think how useful this is for extensibility ?

Tutorial : Early Binding vs Late Binding (Dynamic Binding)SocialTwist Tell-a-Friend

1 comment: