Dai Kaixian
Dai Kaixian

Reputation: 1065

When to use static binding and when to use dynamic binding in Java?

Recently I am learning how to use Slf4j. And I know two new concepts:static binding and dynamic binding.In JCL(Jakarta Commons Logging) it use dynamic binding to choose the implementation while Slf4j is using static binding. In this case we know Slf4j is more wise.But how about other case?

If we meet a problem that we can resolve it both in using static bingding and dynamic binding, then how we choose? Is there any basic rules?

My English is not very good.So I am not sure whether i have made it clear.If you have more question , please comment.

THX.

Upvotes: 0

Views: 1292

Answers (1)

Wearybands
Wearybands

Reputation: 2455

Here : Link

Few important difference between static and dynamic binding

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

2) private, final and static methods and variables uses static binding and bonded by compiler while virtual methods are bonded during runtime based upon runtime object.

3) Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve binding.

3) Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.

Static Binding Example in Java

 public class StaticBindingTest  
 {  
  public static void main(String args[])  
  {
    Collection c = new HashSet();
    StaticBindingTest et = new StaticBindingTest();
    et.sort(c);
  }
  //overloaded method takes Collection argument
  public Collection sort(Collection c)
  {
     System.out.println("Inside Collection sort method");
     return c;
  }
  //another overloaded method which takes HashSet argument which is sub class
 public Collection sort(HashSet hs)
 {
    System.out.println("Inside HashSet sort method");
    return hs;
 }
}

Output: Inside Collection sort method

Example of Dynamic Binding in Java

 public class DynamicBindingTest 
 {
    public static void main(String args[]) 
    {
        Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
        vehicle.start();       //Car's start called because start() is  overridden method
    }
 }

 class Vehicle 
 {
     public void start() 
     {
       System.out.println("Inside start method of Vehicle");
     }
 }
 class Car extends Vehicle 
 {
    @Override
    public void start() 
    {
       System.out.println("Inside start method of Car");
    }
 }

Output: Inside start method of Car

Upvotes: 1

Related Questions