Dynamic Method Binding in Java

Why do we need dynamic method binding? Can we simply bind any method statically at compile time in Java?

No!

Let us see this example:

class Animal{
  public void speak(){
    System.out.println("I am some Animal");
  }
}
class Dog extends Animal{
  public void speak(){
    System.out.println("I am a Dog");
  }
}
class MainProgram{
  public static void main(String args[]){
    Animal a = new Animal();
    Animal b = new Dog();

    // This will print "I am some Animal"
    a.speak();
    // This will print "I am a dog"
    b.speak();
  }
}

The interesting part is that we don’t know the exact type of a variable in the program in run time. For example, check this program:

class MainProgram{
  public static void main(String args[]){
    Animal a;
    if(random_number == 0){
      a = new Animal();
    else{
      a = new Dog();
    }
    // This output cannot be determined in static time!
    a.speak();
  }
}

But we can bind private/static/final methods statically since we will know their behavior in compile time.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *