所以我之前问过这个问题,但大多数人发现我的代码有错误,而不是问题本身。
无论如何,我正在尝试重写类中的接口(interface)方法。但是,我希望覆盖方法中的参数类型是覆盖方法中定义的参数类型的子类。
界面是:
public interface Observer {
public void update(ComponentUpdateEvent updateEvent) throws Exception;
}
虽然重写这个方法的类是:
public class ConsoleDrawer extends Drawer {
//...
@Override
public void update(ConsoleUpdateEvent updateEvent) throws Exception {
if (this.componentType != updateEvent.getComponentType()) {
throw new Exception("ComponentType Mismatch.");
}
else {
messages = updateEvent.getComponentState();
}
}
//...
}
ConsoleUpdateEvent 是 ComponentUpdateEvent 的子类。
现在,我可以让 ConsoleDrawer 中的 update() 方法将 ComponentUpdateEvent 作为参数,然后将其转换为 ConsoleUpdateEvent,但如果可能的话,我正在寻找稍微更优雅的解决方案。任何帮助,将不胜感激。谢谢。
最佳答案
你不能。这不是埃菲尔铁塔。问题是您可以使用接口(interface)调用具有不兼容类型的实现方法。所以协变参数是不允许的。也不允许逆变参数,但提供重载更容易。允许协变返回类型(自 1.5 起)。
你可以参数化接口(interface):
public interface Observer<T extends ComponentEvent> {
void update(T event) throws Exception;
}
或者,使用更有意义的界面:
public interface ConsoleObserver {
void update(ConsoleEvent event) throws Exception;
}
关于Java:在覆盖方法时替换参数的子类/子类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4417938/