Static Binding and Dynamic Binding

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

Understanding Type

Let’s understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.

 int data=30;

Here data variable is a type of int.

2) References have a type

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

3) Objects have a type

An object is an instance of particular java class,but it is also an instance of its superclass.
  1. class Animal{}
  2. class Dog extends Animal{
  3.  public static void main(String args[]){
  4.   Dog d1=new Dog();
  5.  }
  6. }
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding

When type of the object is determined at compiled time(by the compiler), it is known as static binding.

If there is any private, final or static method in a class, there is static binding.

Example of static binding

  1. class Dog{
  2.  private void eat(){System.out.println(“dog is eating…”);}
  3.  public static void main(String args[]){
  4.   Dog d1=new Dog();
  6.  }
  7. }

Dynamic binding

When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding

  1. class Animal{
  2.  void eat(){System.out.println(“animal is eating…”);}
  3. }
  4. class Dog extends Animal{
  5.  void eat(){System.out.println(“dog is eating…”);}
  6.  public static void main(String args[]){
  7.   Animal a=new Dog();
  9.  }
  10. }

Test it Now

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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s