声明:
class Wrapped<Elem extends Copyable<Elem>>
只是说你只能用 .Wrapped的子类型来实例化类型Copyable。注意Elem部分。这意味着子类型Elem应该是 的子类型Copyable<Elem>。
例如,假设您有一个实现该通用接口的类:
interface Copyable<T>{
T copy();
}
class CopyableImpl implements Copyable<CopyableImpl> {
CopyableImpl copy() { ... }
}
现在您可以像这样实例化Wrapped泛型类型CopyableImpl:
Wrapped<CopyableImpl>
替换CopyableImpl为Elem并查看它是否满足声明。
CopyableImpl extends Copyable<CopyableImpl>
Elem extends Copyable<Elem>
所以,它是一个有效的类型参数Wrapped。
但是,如果您的课程是这样的:
class SomeCopyable implements Copyable<OtherCopyable> {
OtherCopyable copy() { ... }
}
您不能Wrapped使用此类实例化泛型类型,因为它不满足Wrapped.
SomeCopyable extends Copyable<OtherCopyable>
Elem extends Copyable<Elem2> // Elem 2 is different from Elem
至于你的提议:
class Wrapped<Copyable<Elem>>
不,此声明与原始声明完全不同。考虑到泛型类型是不变的,从某种意义上说,aList<String>不是 的子类型,List<CharSequence>尽管String它是 的子类CharSequence。因此,对于此声明,您只能使用如下类型参数实例化Wrapped类型:Copyable
Wrapped<Copyable<String>>
Wrapped<Copyable<Integer>>
Wrapped<CopyableImpl> // Wrong. This doesn't match the type declaration.
延伸阅读: