假设我们有课 X
和通用类Y
:
class X {}
class Y<T extends X> {}
为什么以下声明是合法的?
Y<? extends Serializable> obj; //I understand this as any type extends X and Serializable
我的理解是?
表示满足 <T extends X>
的任何类型,包括X
本身。所以, X
的子类实现Serializable
适合这里。然而,X
本身并没有实现Serialized,那么为什么前面的声明可以工作呢?
最佳答案
What I understand is that
?
means any type that satisfies<T extends X>
, includingX
itself.
是的,您已经为变量 obj
添加了附加限制未知类型 ?
代表,必须执行Serializable
.
So, subclasses of
X
that implementSerializable
fits here.
没错。
However,
X
itself does not implementSerializable
, so why does the previous declaration work?
没关系X
不实现Serializable
- 为什么这很重要?
extends Serializable
只是您特别为变量 obj
添加到类型中的附加限制.
注意变量 obj
您只能分配一个扩展 X
的类实例的值并且还实现了 Serializable
.
// Error! X does not implement Serializable, so this is not allowed
Y<? extends Serializable> obj = new Y<X>();
class Z extends X implements Serializable { ... }
// No problem, since Z extends X and also implements Serializable
Y<? extends Serializable> obj = new Y<Z>();
关于Java泛型 - 通配符与接口(interface)绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58623320/