java - 动态方法分派(dispatch)只是为了减少编译时间吗

标签 java dispatch

我是 JAVA 新手,在学习时我遇到了 Dynamic Method Dispatch,这个例子让我很困惑

class A {
   void callme() {
     System.out.println("Inside A's callme method");
  }
}

class B extends A {
  // override callme()
  void callme() {
    System.out.println("Inside B's callme method");
  }
}

class C extends A {
  // override callme()
  void callme() {
    System.out.println("Inside C's callme method");
  }
}

class Dispatch {
  public static void main(String args[]) {
    A a = new A(); // object of type A
    B b = new B(); // object of type B
    C c = new C(); // object of type C
    A r; // obtain a reference of type A    

    r = a; // r refers to an A object
    r.callme(); // calls A's version of callme

    r = b; // r refers to a B object
    r.callme(); // calls B's version of callme

    r = c; // r refers to a C object
    r.callme(); // calls C's version of callme
  }
}

如果我这样做

a.callme();
b.callme();
c.callme();

我得到了相同的结果。 当我通过谷歌搜索了解 DMD 时,我没有得到令人满意的解释。我只知道它是后期绑定(bind)而不是早期绑定(bind),仅此而已。所以它只是在编译时用来转义还是有别的什么用。有没有简单的例子来理解其好处。

最佳答案

这通常称为动态绑定(bind)。它提供了多态行为(多态是一个OOP概念)。

在Java中,动态绑定(bind)是根据对象的实际类型来完成的。这意味着无论对象的声明类型如何,调用的方法体都将是在用于构造该对象的类(运行时类)中声明的方法体。这是使用 new 的类。

当您分配r = a并调用r.callme()时,Java(在运行时)将看到变量所代表的对象的类>r指向的是A,因此将运行类A提供的callme()实现。 同样,当您重新分配r = b并调用r.callme()时,Java将看到该对象的类是B并且将运行B.callme

关于“为什么”部分,Java tutorial有状态:

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.

关于java - 动态方法分派(dispatch)只是为了减少编译时间吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53035070/

相关文章:

java - 动态调度、重载和泛型

java - Android Glide 库 NoClassDefFoundError

java - 在java中使用递归方法进行内存

java - 当数据库关闭时阻止工作线程的最佳同步策略

typescript - 如何在 typescript 中动态调用实例方法?

android - 如何知道标签是否存在?

php - Apache proxfy_fcgi - 将请求分派(dispatch)到时出错

java - @GenerationType.IDENTITY 失败超过 10

java - 是否有可能有一个可以执行 R 脚本的独立 spring boot jar ?

Javascript方法调度过程