什么是java中的调度 [英] What is dispatching in java

查看:277
本文介绍了什么是java中的调度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对确切的调度感到困惑。特别是在双重调度方面。有没有一种简单的方法可以理解这个概念?

I am confused on what exactly dispatching is. Especially when it comes to double dispatching. Is there a simple way that I can grasp this concept?

推荐答案

Dispatch是语言链接调用函数/方法定义的方式。

Dispatch is the way a language links calls to function/method definitions.

在java中,一个类可能有多个具有相同名称但参数类型不同的方法,并且该语言指定使用正确的数字将方法调用分派给方法具有实际参数可以匹配的最具体类型的参数。这是静态派遣。

In java, a class may have multiple methods with the same name but different parameter types, and the language specifies that method calls are dispatched to the method with the right number of parameters that has the most specific types that the actual parameters could match. That's static dispatch.

例如,

void foo(String s) { ... }
void foo(Object o) { ... }
{ foo("");           }  // statically dispatched to foo(String)
{ foo(new Object()); }  // statically dispatched to foo(Object)
{ foo((Object) "");  }  // statically dispatched to foo(Object)

Java还有虚方法调度。子类可以覆盖超类中声明的方法。因此,在运行时,JVM必须将方法调用分派给适合运行时类型 this 的方法版本。

Java also has virtual method dispatch. A subclass can override a method declared in a superclass. So at run-time, the JVM has to dispatch the method call to the version of the method that is appropriate to the run-time type of this.

例如,

class Base { void foo() { ... } }
class Derived extends Base { @Override void foo() { ... } }


{ new Derived().foo(); }  // Dynamically dispatched to Derived.foo.
{
  Base x = new Base();
  x.foo();                // Dynamically dispatched to Base.foo.
  x = new Derived();      // x's static type is still Base.
  x.foo();                // Dynamically dispatched to Derived.foo.
}

双重发送静态和运行时(也称为动态)调度。

Double-dispatch is the combination of static and run-time(also called dynamic) dispatches.

这篇关于什么是java中的调度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆