简体   繁体   English

Java generics - 带有接口绑定问题的通配符

[英]Java generics - wildcard with interface bound question

Suppose that we have class X and generic class Y :假设我们有 class X和通用 class Y

class X {}

class Y<T extends X> {}

Why is the following declaration legal?为什么以下声明是合法的?

Y<? extends Serializable> obj; //I understand this as any type extends X and Serializable

What I understand is that ?我的理解是这样的? means any type that satisfies <T extends X> , including X itself.表示满足<T extends X>的任何类型,包括X本身。 So, subclasses of X that implement Serializable fits here.因此,实现SerializableX子类适合这里。 However, X itself does not implement Serializable, so why does the previous declaration work?但是X本身并没有实现Serializable,那么为什么前面的声明行得通呢?

This is valid because in ? extends Serializable这是有效的,因为在? extends Serializable ? extends Serializable ? ? extends Serializable is not determined yet & ?还没确定& ? class must be implementing Serializable while it must be extending X per this definition. class 必须实现Serializable ,而它必须根据此定义扩展X So, as soon as you provide assignment to this reference variable a type check would be done for that object (generics are to detect type error at compile time).因此,一旦您为该引用变量赋值,就会对该 object 进行类型检查(泛型用于在编译时检测类型错误)。 The object must inherit Serializable as well as X else error will be shown. object 必须继承 Serializable 以及 X 否则将显示错误。

What I understand is that ?我的理解是这样的? means any type that satisfies <T extends X> , including X itself.表示满足<T extends X>的任何类型,包括X本身。

Yes, and you've added the additional restriction for the variable obj that the unknown type which ?是的,并且您为变量obj添加了未知类型 which 的附加限制? stands for, must implement Serializable .代表,必须实现Serializable

So, subclasses of X that implement Serializable fits here.因此,实现SerializableX子类适合这里。

That's right.这是正确的。

However, X itself does not implement Serializable , so why does the previous declaration work?但是, X本身并没有实现Serializable ,那么为什么前面的声明有效呢?

It doesn't matter that X does not implement Serializable - why should this matter? X没有实现Serializable并不重要——为什么这很重要?

The extends Serializable is just an additional restriction that you added to the type particularly for the variable obj . extends Serializable只是您添加到类型的附加限制,特别是对于变量obj

Note that to the variable obj you can only assign a value that is an instance of a class that extends X and that also implements Serializable .请注意,您只能为变量obj分配一个值,该值是 class 的一个实例,它扩展了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>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM