Java newbie here. Here’s what I’d like to do:
- Enumerate over a list of classes, each of which extends the same superclass.
- Ask the class whether it’s interested in an event.
- If the class is interested, instantiate the class and call the object’s event handler.
The idea is that steps 2 and 3 will prevent instantiation of classes that aren’t interested. However, because I’m calling a method before instantiation, the check would have to be done statically. Java (rightly) doesn’t allow the overriding of static methods, so it seems that I have to instantiate the class in step 2, making the sequence look like this:
- Enumerate over a list of classes, each of which extends the same superclass.
- Instantiate each class and ask the object whether it’s interested in the event.
- If the object is interested, call its event handler. If it’s not interested, throw it away.
Am I missing a general way to accomplish the first set of steps?
Note that this question is mostly theoretical. Object creation overhead may be low enough to render it moot. I’m interested in the possibilities, though.
Since we’re speaking about theory, I’m pointing at some facts and speaking in terms of design.
Static methods are not associated to a particular instance of a class, so overriding is not an option since it depends on having an instance. I’m talking about Java, because I recall some other languages that allow class method overriding.
The workaround to this is to define a static method in each subclass that returns the events it is interested in, so you can know this data before instantiation.
Another option is to put a specific class in charge of those objects instantiation and making that class keep a table associating an event with a list of interested classes (table that you can initialize and configure). This approach seems more maintainable because you won’t have to change code if you want to unsuscribe a class from an event.
In the end, you just instantiate all the classes thata re associated to a certain event: