Thursday , November 7 2024

Static Binding and Dynamic Binding in Java

Connecting a method call to the method body is known as binding.

There are two types of binding

  1. static binding (also known as early binding).
  2. dynamic binding (also known as late binding).

1. Static binding or Early binding

Static binding is a binding which happens during compilation. It is also called early binding because binding happens before a program actually runs.
If there is any private, final or static method in a class, there is static binding.
Static binding example

class Human{
....
}
class Boy extends Human{
public void walk(){
System.out.println("Boy walks");
}
public static void main( String args[]) {
Boy obj1 = new Boy();
obj1.walk();
}
}

Here we have created an object of Boy class and calling the method walk() of the same class. Since nothing is ambiguous here, compiler would be able to resolve this binding during compile-time, such kind of binding is known as static binding.

2.Dynamic Binding or Late Binding

When compiler is not able to resolve the call/binding at compile time, such binding is known as Dynamic or late Binding. Overriding is a perfect example of dynamic binding as in overriding both parent and child classes have same method.
Thus while calling the overridden method, the compiler gets confused between parent and child class method(since both the methods have same name).

Example of dynamic binding

 

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 Dog();
a.eat();
}
}

Output:dog is eating...

In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instance of Animal.So compiler doesn’t know its type, only its base type.

Static Binding vs Dynamic Binding

Lets discuss the difference between static and dynamic binding in Java.

  1. Static binding happens at compile-time while dynamic binding happens at runtime.
  2. Binding of private, static and final methods always happen at compile time since these methods cannot be overridden. Binding of overridden methods happen at runtime.
  3. Java uses static binding for overloaded methods and dynamic binding for overridden methods.

About admin

Check Also

Arrays in java

The array is a data structure which stores a fixed-size sequential collection of elements of …

Leave a Reply