Java - What is Static and Dynamic binding

http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html

Sometimes I can't open this page without proper proxy configuration, so I have to copy the content here.


If you have more than one method of same name (method overriding) or two variable of same name in same class hierarchy,  it gets tricky to find out which one is used during runtime. This problem is resolved using static and dynamic binding in Java.

Static Binding vs 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.
4) 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

In above example of static binding in Java we have overloaded sort() method, one of which accept Collection and other accept HashSet. we have called sort() method with HashSet as object but referenced with type Collection and when we run method with collection as argument type gets called because it was bonded on compile time based on type of variable (Static binding)  which was collection.

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


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值