Dynamic and Static binding - Coddicted

Dynamic and Static binding

Dynamic binding means the runtime finds the type of an object (probably from its Class<T> object) and uses that type to look for the types of methods invoked. It applies to overridden class members. And the only kind of class member you can override is an instance method.
 
Static binding means the compiler finds the type of an object from the declaration of its reference and uses that type to look for the types of members. That applies to non-overridden class members, i.e. static fields and methods.
 
For example:
class A

    int num = 10; 
    int get()
    { 
        return num; 
    } 
class B extends A 

    int num = 20; 
    int get()
    { 
        return num; 
    } 
class Test

    A a = new A(); 
    A a1 = new B();
    System.out.println(a.num);//10 ->  Reason: static  binding
    System.out.println(a1.num);//10 -> Reason: static binding
    System.out.println(a.get()); //10 -> Reason : dynamic binding
    System.out.println(a1.get()); //20 -> Reason : dynamic binding
}
 
source: Java Ranch

Back To Top
Rate this post

Leave a Reply