gpt4 book ai didi

具有泛型的 Java 接口(interface)应接受子类作为类型参数

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:04:40 25 4
gpt4 key购买 nike

我现在有以下类层次结构:

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,接口(interface)应该接受任何扩展 T 的元素 E?或者是 Wrapper 的原因?我试过包装器:

class Wrapper<E extends Interface<? extends E>> {}

这在包装器主体中产生了错误,并且没有改变原始错误。

Wrapper<Base> wrapper = new Wrapper<Base>();

工作正常...我该怎么做

Wrapper<Subclass> wrapper = new Wrapper<Subclass>();

也工作?有没有任何 Actor 的干净方式? (允许通配符)

谢谢!

最佳答案

尝试

class Wrapper<E extends Interface<? super E>>

就像Comparable , 它直观上是一个 'contra-variant'类型,因此在大多数情况下它应该与 <? super> 一起使用.例如Collections.sort

关于具有泛型的 Java 接口(interface)应接受子类作为类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40848072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com