I have an abstract class AbstractEvent and some “real” classes extending it. I want to make an abstract class AbstractListener with a method process(??? event) so that non-abstract classes extending AbstractListener would be required to have at least one method accepting a class extending AbstractEvent. Is that possible?
I have an abstract class AbstractEvent and some real classes extending it. I want
Share
You’ve already got the name of the mechanism you want – generics!
First, make your event class:
Nothing strange about that. Next, create a parameterized listener class/interface, and give its type parameter an upper bound to your event object class:
You can now go on making your specific event classes:
And, well, that should be pretty much all you need. Go on and implement your listener classes:
Now, you may be tempted to write a generic event dispatching class like this:
Looks pretty sweet, eh? You can do stuff like this:
Totally sweet, we can just use this stuff, and then when we’ve used it, just keep on reusing it. There’s one problem though. Assume you’ve got a clever developer who wants a super-simple listener that doesn’t actually do anything with the event object, but just prints a specified message whenever the event occurs.
Not really considering your awesome
EventDispatcherutility class, it was written thus:This should be reusable, right? No. This wouldn’t work:
Because
DebugListeneris aListener<AbstractEvent>, not aListener<PonyEvent>. The way to solve this would be to use a lower bound for the parameter type:This gives you the behaviour you’re after: Just like you can send a
PonyEventto theprocessmethod of aListener<AbstractEvent>(because aPonyEventis-anAbstractEvent), you can now use the event dispatcher class parameterized with a type to fire listeners parameterized with one of its supertypes.