[英]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.