Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Patterns to compensate for lack of runtime method lookup based on polymorphic args in Java?

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?

like image 277
brabster Avatar asked Dec 22 '22 21:12

brabster


2 Answers

Visitor pattern is what you need

like image 59
khachik Avatar answered Dec 24 '22 10:12

khachik


These situations are when I think of Visitor or double dispatch pattern.

like image 44
duffymo Avatar answered Dec 24 '22 11:12

duffymo