Example & Tutorial understanding programming in easy ways.

What is the difference between static and dynamic binding ?

What is the difference between static and dynamic binding ?

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.

public class vehical {

public void getName(){

System.out.println("My name is vehical !"); }

public class car extends vehical {

    //Override

public void getName() {

System.out.println("My name is car !"); }

}

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.

vehical vehi = new car();

vehi.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 static binding .

 example :-

public class vahical {

public static void staticPart(){

System.out.println("I am static part of vahical !");

} }

public class car extends vahical {

//this is not a overriden method

public static void staticPart() {

System.out.println("I am static part of car !");

}

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

car.staticPart();

vahical .staticPart();

} }

Read More →