on Leave a Comment

Static and Dynamic Binding in Java

Binding is the association of method call to method body. Binding can be done at compile time and run time. Compile time binding is known as static binding and run time binding is known as dynamic binding.

Static Binding

In static binding, method call is associated with method body at the compile time. When we overload methods, it is important to resolve binding. In case of overloaded methods, binding is resolved at compile time. But we override method, binding cannot be resolved at compile time. Static binding uses only Type information for binding. Binding of methods such as static, private and final is always static binding. Because static, private and final methods cannot be overridden, so they can be only called by object of local class (static method is called by class name). So, binding of static, private and final method needs only Type information.

Example

class ParentClass{
    static void show(){
        System.out.println("Parent Class");
    }
}
public class ChildClass extends ParentClass {
    static void show(){
        System.out.println("Child Class");
    }
    public static void main(String[] args){
        ParentClass obj1 = new ChildClass();
        ParentClass obj2 = new ParentClass();
        obj1.show();
        obj2.show();
    }
}

Output:

Parent Class
Parent Class

Dynamic Binding

Dynamic binding is done at run time. When both parent class and child class defines the same method, in this case object type determines which method to call. And type of object is determined at run time. So, binding of overridden methods is always a dynamic binding.

Example

class ParentClass{
    void show(){
        System.out.println("Parent Class");
    }
}
public class ChildClass extends ParentClass {
    void show(){
        System.out.println("Child Class");
    }
    public static void main(String[] args){
        ParentClass obj1 = new ChildClass();
        ParentClass obj2 = new ParentClass();
        obj1.show();
        obj2.show();
    }
}

Output:

Child Class
Parent Class



0 comments:

Post a Comment