简体   繁体   English

当变量是抽象父类时,Java将分派给子类

[英]Java dispatch to child class when variable is of abstract parent class

I have an abstract parent class Parent and six child classes ChildA though ChildF . 我有一个抽象的父类Parent和六个子类ChildA ChildF

Another class Other has a six (static) overloaded methods olmeth() , one for each of the six child classes. 另一个类Other具有六个(静态)重载方法olmeth() ,六个子类中的每个都有一个。

How can I write: 我该怎么写:

Parent message = Factory.returnRandomChildClass();
Other.olmeth(message);

At the moment I use an extra method, overloaded for the parent class, and six instanceof checks to work around this issue. 目前,我使用了一个额外的方法,为父类重载了该方法,并使用了六个instanceof检查来解决此问题。 This is unscalable. 这是不可扩展的。

How can I get Java to dispatch on the actual type of message , rather on the type of the reference to the message? 如何使Java根据message实际类型进行调度,而不是根据message引用类型进行调度?

Make an abstract method in the Parent , and let each child dispatch to its own static overload: Parent一个抽象方法,并让每个子节点分派给它自己的static重载:

abstract class Parent {
    protected abstract void send();
}
class ChildA extends Parent {
    protected void send() {
        Other.olmeth(this);
    }
}
class ChildB extends Parent {
    protected void send() {
        Other.olmeth(this);
    }
}
...
class ChildF extends Parent {
    protected void send() {
        Other.olmeth(this);
    }
}

Note that although the code in all six implementations of send() look exactly the same, the methods actually dispatch to six different overloads of Other , because the static type of this in each case is different. 请注意,尽管send()所有六个实现中的代码看起来都完全相同,但是这些方法实际上分派给Other六个不同重载,因为在每种情况下, this的静态类型都是不同的。

Use double dispatch pattern. 使用双调度模式。 Implement the olmeth logic for every Parent child class and change your current olmeth method to this: 为每个Parent子类实现olmeth逻辑,并将当前的olmeth方法更改为:

 static void olmeth(Parent p) {
     p.olemth();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM