Search code examples
javainheritancemethodssubclasssuperclass

Override a class' method by iterating over a subclass


This is a complicated problem to explain so I did a crappy MSPaint diagram.

enter image description here

Say I have a list of Subclass objects. Some of them contain a method called onEvent();. Inside my onEvent(); from a completely unrelated class I want to iterate through my list of objects and call their onEvent();s if they exist. Obviously if I try to iterate through a list of type Superclass it must be an abstract method to work. I only want a certain few subclasses to have this onEvent() method.

I might have made it hard to understand but I hope you get it, any ideas would be appreciated.


Solution

  • I think you should rethink your class design.

    There are two solutions to your problem

    1. Pull the onEvent method up into your super class as non-abstract method with empty body. Then you can override in subclasses only where appropriate.

    2. Introduce an interface - let's call it EventHandler - that declares the method onEvent. Implement this interface in your subclasses where appropriate. Then either change your list to be a list of EventHandler objects or leave it as is and use instanceof to check if an object is an EventHandler in your iteration.