我是 Java 新手,我有些疑问。例如,考虑这样的表达式:
a.method()
a.method("string")
人们称之为“动态调度”。但我确信类型检查器确保名为
method()
、method(String a)
的方法可用于对象 a
。
但是为什么叫“动态”呢?这不是静态调用吗?既然编译器已经发现了?
您发布的示例不会使用动态调度。您发布了
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
。
您显示的代码不表达动态调度(绑定)。请看下面的代码。
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)
}
}