Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Binding and Dynamic Binding

I am really confused about dynamic binding and static binding. I have read that determining the type of an object at compile time is called static binding and determining it at runtime is called dynamic binding.

What happens in the code below:

Static binding or dynamic binding?
What kind of polymorphism does this show?

class Animal {     void eat()     {         System.out.println("Animal is eating");     } }  class Dog extends Animal {     void eat()     {         System.out.println("Dog is eating");     } }  public static void main(String args[]) {     Animal a=new Animal();     a.eat(); } 
like image 282
Abhinav Avatar asked May 20 '13 10:05

Abhinav


People also ask

What is difference between static binding and dynamic binding?

The static binding uses Type information for binding while Dynamic binding uses Objects to resolve to bind. Overloaded methods are resolved (deciding which method to be called when there are multiple methods with the same name) using static binding while overridden methods use dynamic binding, i.e, at run time.

What is dynamic binding?

Dynamic binding or late binding is the mechanism a computer program waits until runtime to bind the name of a method called to an actual subroutine. It is an alternative to early binding or static binding where this process is performed at compile-time.

What is static binding also called?

Static Binding (also known as Early Binding). Dynamic Binding (also known as Late Binding).


1 Answers

Your example is dynamic binding, because at run time it is determined what the type of a is, and the appropriate method is called.

Now assume you have the following two methods as well:

public static void callEat(Animal animal) {     System.out.println("Animal is eating"); } public static void callEat(Dog dog) {     System.out.println("Dog is eating"); } 

Even if you change your main to

public static void main(String args[]) {     Animal a = new Dog();     callEat(a); } 

this will print Animal is eating, because the call to callEat uses static binding, and the compiler only knows that a is of type Animal.

like image 108
Vincent van der Weele Avatar answered Sep 29 '22 19:09

Vincent van der Weele