fadedbee
fadedbee

Reputation: 44745

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?

Upvotes: 1

Views: 92

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

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.

Upvotes: 2

ka4eli
ka4eli

Reputation: 5424

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();
 }

Upvotes: 1

Related Questions