It seems that Java can't choose the most appropriate method implementation based on the runtime type of an argument, as documented here. Recapitulating the example:
class Superclass {}
class Subclass extends Superclass {}
class Test {
public void aMethod(Superclass s) {...}
public void aMethod(Subclass s) {...}
}
Which method of the Test class is executed is determined based on the type of the reference, not the type of the instance. Again, based on the linked examples:
Test aTest = new Test();
Superclass aSuper = new Subclass();
test.aMethod(aSuper);
It is aMethod(Superclass s)
that executes, not aMethod(Subclass s)
.
I was trying to create a variation on the listener pattern, where listeners 'plug in' via an interface, and the listeners have methods defined for subclasses of the interfaces.
As a quick example of what I mean, say I'm building an alarm clock that can have functionality plugged in.
The implementation for the above I had in mind would look like an interface Event
, with a subclass WakeUpEvent
, and an interface EventListener
requiring implementation of handle(Event evt)
.
I hoped to create a class implementing a no-op handle(Event evt)
with a specific handle(WakeUpEvent evt)
if the listener wanted to deal with that type of event.
Of course, this approach won't work as-is - the obvious solution is runtime instanceof
checks - yuk.
Are there any patterns or approaches that I can use to get the behaviour I want?
Visitor pattern is what you need
These situations are when I think of Visitor or double dispatch pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With