Tuesday, February 25, 2014

What is the difference between static binding and dynamic binding?


Dynamic Binding refers to the case where compiler is not able to resolve the call and the binding is done at runtime only
Dynamic Binding:
SuperClass superClass1 = new SuperClass();
SuperClass superClass2 = new SubClass();
superClass1.someMethod(); // SuperClass version is called
superClass2.someMethod(); // SubClass version is called
Static Binding:
Class SubClass extends SuperClass{
public String someVariable = "Some Variable in SubClass";
}
SuperClass superClass1 = new SuperClass();
SuperClass superClass2 = new SubClass();
System.out.println(superClass1.someVariable);
System.out.println(superClass2.someVariable);
Output:-
Some Variable in SuperClass
Some Variable in SuperClass



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.
  1. int data=30;  
Here data variable is a type of int.

2) References have a type

  1. class Dog{  
  2.  public static void main(String args[]){  
  3.   Dog d1;//Here d1 is a type of Dog  
  4.  }  
  5. }  

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.   
  3. class Dog extends Animal{  
  4.  public static void main(String args[]){  
  5.   Dog d1=new Dog();  
  6.  }  
  7. }  
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.   
  4.  public static void main(String args[]){  
  5.   Dog d1=new Dog();  
  6.   d1.eat();  
  7.  }  
  8. }  

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.   
  5. class Dog extends Animal{  
  6.  void eat(){System.out.println("dog is eating...");}  
  7.   
  8.  public static void main(String args[]){  
  9.   Animal a=new Dog();  
  10.   a.eat();  
  11.  }  
  12. }  
Output:dog is eating...

No comments:

Post a Comment