Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Sunday, 13 October 2013

Difference between Static and Dynamic binding in Java

In this particular blog we will see a very frequently asked interview question i.e. "Difference between Static and Dynamic binding in Java".

In static binding, the method or variable version that is going to be called is resolved at compile time, while in dynamic binding the compiler could not resolve which version of a method or variable is going to bind.



Dynamic Binding in Java - Late Binding

If we have two methods or variable with same name in a class hierarchy than it becomes tricky to find which version is going to called at compile time, this scenario is called Dynamic Binding.
/**
 * @author Nagesh Chauhan
 */
public class Fruit {
 public void getName(){
  System.out.println("My name is fruit !");
 }
 
}

public class Apple extends Fruit {
 @Override
 public void getName() {
  System.out.println("My name is apple !");
 }

}

public class Implementation {

 public static void main(String[] args) {
  /*
   * This is called Dynamic binding, as the compiler will never know which
   * version of getName() is going to called at runtime.
   */
  Fruit fruit = new Apple();
  fruit.getName();
 }
}



Static Binding in Java - Early Binding

If Static Binding or Early Binding, the compiler can resolves the binding at compile time. All the static method calls are resolved at compile time itself because static methods are class methods and they are accessed using the class name itself. Hence there is no confusion for compiler to resolve, which version of the method is going to be called. See the example below :
/**
 * @author Nagesh Chauhan
 */
public class Fruit {
 
 public static void staticPart(){
  System.out.println("I am static part of fruit !");
 }
}

public class Apple extends Fruit {

 /*
  *  this is not a overriden method 
  */
 public static void staticPart() {
  System.out.println("I am static part of apple !");
 }
}

public class Implementation {

 public static void main(String[] args) {
  /*
   * This is an example of static binding, static members are called with
   * class name and hence, binding is resolved at compiletime itself.
   */
  Apple.staticPart();
  Fruit.staticPart();

 }

}





Here we are done with 'Difference between Static and Dynamic binding in Java'. In our upcoming blogs we will see more about Java Programming and other opensource technologies.








Thanks for reading !
Being Java Guys Team




3 comments:

  1. Very nice tutorial... easily understandable...Thanks...

    ReplyDelete
  2. Some more on this topic :

    http://goo.gl/nZBtgA

    ReplyDelete
  3. why overloading is considered to be staic binding?

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft