blog

Home / DeveloperSection / Blogs / Static Binding and Dynamic Binding in Java

Static Binding and Dynamic Binding in Java

Manoj Pandey2563 23-Apr-2015

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).

Static binding in Java occurs during Compile time while Dynamic binding occurs during Runtime.

Instance type-:

1. Variable-: variable is a type. It may be primitive and non-primitive. For example

int a=10;


2. Reference-: Reference is also instance type. It contains reference to a class, interfaces, etc. e.g.

class Dog{  
 public static void main(String args[]){ 
  Dog d1;//Here d1 is a type of Dog 
 } 
}


3. Object-: Object is also instance type. The object contains current class reference as well as superclass reference.

class Animal{}  
class Dog extends Animal { 
  public static void main(String args[]) { 
  Dog d1=new Dog(); 
  } 
}


Static binding -: The binding which can be resolved at compile time by the compiler is known as static or early binding. All the static, private and final methods have always been bonded at compile-time

Example of Static Binding

class Human{

}

class Boy extends Human{

   publicvoid Run(){

      System.out.println("Boy runs");

   }

   publicstaticvoid main( String args[]) {

      Boy obj1 = new Boy();

      obj1.Run();

   }

 

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

 

Dynamic binding-: When the compiler is not able to resolve the call/binding at compile time, such binding is known as Dynamic or late Binding.

Example of dynamic binding

class Human{

         publicvoid walk()

         {

             System.out.println("Human walks");

         }

      }

      class Boy extends Human{

         publicvoid walk(){

             System.out.println("Boy walks");

         }

         publicstaticvoid main( String args[]) {

             //Reference is of parent class

             Human myobj = new Boy();

             myobj.walk();

         }

      }

 

Difference between static binding and Dynamic binding

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

Updated 24-Feb-2018

Leave Comment

Comments

Liked By