I have an interface (called Subject
) that has the following method:
public void addObserver(Observer o);
I then have another interface that extends Subject
called TimerSubject
. This interface is a more specific version of Subject
, used for timing. It has a few other miscellaneous methods.
There are also the two corresponding interfaces, Observer
, and TimerObserver
. TimerObserver
extends Observer
.
When a class implements TimerSubject
, it has to override the addObserver()
method from the Subject
interface. That looks like this:
@Override
public void addObserver(**Observer e**) {
observers.add(e);
}
The problem is, I need the method to accept a TimerObserver
instead of Observer
, whitch would look like this:
@Override
public void addObserver(**TimerObserver e**) {
observers.add(e);
}
This does not work, since the arguments are not the same as the arguments from the method being overridden.
So is there a way to override a method with arguments that are polymorphic?
A few solutions come to mind:
Your TimerSubject implementation could implement public void addObserver (Observer) by throwing a RuntimeException if it receives an argument that is not a TimerObserver. You lose the protection of the compiler forcing types on you, but late binding is fairly typical to "true" polymorphism.
Alternatively, your TimerSubject interface could simply specify a new method, addTimerObserver, for the new behavior. Presumably your TimerSubject extends a Subject which already has an implementation of addObserver(Observer); if that implementation would be entirely defunct, you can override and throw an error. But if TimerSubject really has no use for an addObserver(Observer) method and that method is entirely defunct, then perhaps these two objects are not as polymorphic as you'd like. :)