简体   繁体   中英

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 .

Another class Other has a six (static) overloaded methods olmeth() , one for each of the six child classes.

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. 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?

Make an abstract method in the Parent , and let each child dispatch to its own static overload:

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.

Use double dispatch pattern. Implement the olmeth logic for every Parent child class and change your current olmeth method to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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