在带泛型的子类型的继承接口中覆盖方法 [英] Override method in inherited interface with subtype with generics

查看:399
本文介绍了在带泛型的子类型的继承接口中覆盖方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  interface ObserverA {} 

interface A {
void method1();
addObserver(Observer o);
}

我想像这样扩展它:

  interface ObserverB extends ObserverA {} 

interface B extends A {
void method2();
addObserver(ObserverB o);

,这样 addObserver()方法 B 会覆盖 A 中的相同方法。
因为它不起作用,所以 B 的实现需要实现 addObserver()

这可以通过一种巧妙的方式来完成,而不需要参数化 A ,例如:

  interface A< O extends Observer> {
addObserver(O o);
}

黑客解决方案非常受欢迎!

解决方案

不能缩小子接口或子类中的方法参数类型。你只能扩大它们,因为子类型的实现必须能够满足超类型的合约。同样,你可以缩小返回类型和异常,但不能扩大范围他们,出于同样的原因。


I have the following hierarchy in java:

interface ObserverA {}

interface A {
  void method1();
  addObserver(Observer o);
}

And I want to extend it like this:

interface ObserverB extends ObserverA{}

interface B extends A {
   void method2();
   addObserver(ObserverB  o);
}

in such a way that the addObserver() method of B would override the same method in A. As it is it doesn't work, implementations of B would need to implement both versions of addObserver(), I wan't to have just one.

Can this be done in a clever way that doesn't involve having to parameterize A like:

interface A<O extends Observer> { 
    addObserver(O o);
}

Hackish solutions are most welcome!

解决方案

You can't narrow method parameter types in subinterfaces or subclasses. You can only broaden them, since implementations of the subtype must be able to fulfill the contract of the supertype.

Similarly, you can narrow return types and exceptions, but not broaden them, for the same reason.

这篇关于在带泛型的子类型的继承接口中覆盖方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆