【发布时间】:2016-11-28 15:35:12
【问题描述】:
我现在有以下类层次结构:
interface Interface<T> {
boolean isGreaterThan(T other);
}
class Base implements Interface<Base> {
public boolean isGreaterThan(Base other) {
return true;
}
}
class Subclass extends Base {
... //note that I dont need to implement or overwrite isGreaterThan() here
}
class Wrapper<E extends Interface<E>> {
protected List<E> list;
...
}
class Test {
public static void main(String[] args) {
Wrapper<Subclass> = new Wrapper<Subclass>(); //This line produces the error
}
}
我收到以下错误消息:
Type parameter 'Subclass' is not within its bound; should implement 'Interface<Subclass>'
我的问题是:我如何告诉 java,接口应该接受任何扩展 T 的元素 E?还是 Wrapper 中的原因?我尝试了 Wrapper:
class Wrapper<E extends Interface<? extends E>> {}
它在包装器的主体中产生了错误,并且没有改变原始错误。
Wrapper<Base> wrapper = new Wrapper<Base>();
工作得很好... 我该怎么做
Wrapper<Subclass> wrapper = new Wrapper<Subclass>();
也可以吗? 有没有没有任何演员的干净方式? (允许使用通配符)
谢谢!
【问题讨论】:
-
class Wrapper<E extends Interface<? super E>> -
这并没有改变任何东西,谢谢你的帮助!
-
<? super E>:) 另见示例docs.oracle.com/javase/7/docs/api/java/util/… -
我试过了,但错误仍然存在;-)
-
哦,我还有其他错误使您的建议复杂化,但我可以弄清楚,这是因为内部类泛型,我只需要输入您的 '?那里也扩展了'解决方案......现在整个事情都有效了!非常感谢!您想将此作为答案发布,以便我将其标记为答案吗?
标签: java generics inheritance interface generic-type-argument