为什么叫动态绑定,而不是静态绑定?

问题描述 投票:0回答:2

我是 Java 新手,我有些疑问。例如,考虑这样的表达式:

a.method()
a.method("string")

人们称之为“动态调度”。但我确信类型检查器确保名为

method()
method(String a)
的方法可用于对象
a

但是为什么叫“动态”呢?这不是静态调用吗?既然编译器已经发现了?

java
2个回答
7
投票

您发布的示例不会使用动态调度。您发布了

Method Overloading
的示例。
Overloading
情况下的方法调用决定是在编译时完成的。编译器根据传递的
formal parameters
actual arguments
来决定调用哪个方法。


当您使用

Dynamic Binding

 时,
Method Overriding
就会发挥作用,其中实际调用哪个方法的决定会延迟到运行时。

例如:-

class A {
    public void demo() { }
}

class B extends A {
    public void demo() { }
}

public class Test {
    public static void main(String[] args) {
        A a = new B();
        a.demo();   // B class method will be invoked.

        A obj = new A();
        obj.demo();  // A class method will be invoked.
    }
}

调用哪个方法是根据特定引用指向哪个类实例来决定的,而这只有在

runtime
处才能知道。因此
Dynamic Dispatch


1
投票

您显示的代码不表达动态调度(绑定)。请看下面的代码。

class Super {
  public void method() {}
}

class Sub extends Super {
  public void method() {}

  public static void main(String... args) {
    Super inst = new Sub();
    inst.method(); //Sub's method() would be invoked.(Express's Dynamic Dispatch)
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.