【问题标题】:Regarding static and dynamic binding in Java关于Java中的静态和动态绑定
【发布时间】:2012-04-28 04:03:02
【问题描述】:

请解释一下Java中静态绑定和动态绑定的概念。

我所掌握的是Java中的静态绑定发生在编译时,而动态绑定发生在运行时,静态绑定使用Type(Java中的类)信息进行绑定,而动态绑定使用Object来解析绑定。

这是我理解的代码。

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

上述程序的输出在集合排序方法中

用于动态绑定...

    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");
    }
}

输出在 Car 的 start 方法中。请指教:这种理解是否正确,请指教更多例子。谢谢。

【问题讨论】:

  • 这似乎是现在的常态……

标签: java


【解决方案1】:

静态绑定在编译时使用,通常与重载方法一起使用 - 您示例中的 sort() 方法,其中 argument(s) 的类型在编译时用于解析方法。

动态绑定 (dynamic dispatch) 通常与多态性和覆盖方法相关联 - 您的示例中的 start() 方法在运行时使用 receiver(车辆)的类型来解决方法。

【讨论】:

    【解决方案2】:

    我认为您已经正确总结了它,并且 shams 也正确地为您添加了更多信息。为了给您添加更多信息,首先让我退后一步,说明方法定义与方法调用的关联称为绑定。因此,正如您正确指出的那样,静态绑定是可以在编译时由编译器解析的绑定(也称为早期绑定或静态绑定)。另一方面,动态出价或后期绑定意味着编译器无法在编译时解析调用/绑定(它发生在运行时)。请参阅下面的一些示例:

    //static binding example
    class Human{
    ....
    }
    class Boy extends Human{
       public void walk(){
          System.out.println("Boy walks");
       }
       public static void main( String args[]) {
          Boy obj1 = new Boy();
          obj1.walk();
       }
    }  
    
    //Overriding is a perfect example of Dynamic binding
    package beginnersbook.com;
    class Human{
       public void walk()
       {
           System.out.println("Human walks");
       }
    }
    class Boy extends Human{
       public void walk(){
           System.out.println("Boy walks");
       }
       public static void main( String args[]) {
           //Reference is of parent class
           Human myobj = new Boy();
           myobj.walk();
       }
    }
    

    source

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      相关资源
      最近更新 更多