Java代码:
class Animal {}
class Cat extends Animal {}
class Box<T> {}
public class Test {
public void hello(Box<? extends Animal> box) {}
}
Box<Animal> box1 = new Box<Animal>();
Box<Cat> box2 = new Box<Cat>();
new Test().hello(box1);
new Test().hello(box2);
来自Liskov Substitution Principle ,自 box2
类型 Box<Cat>
可以在需要类型 Box<? extends Animal>
的地方使用,我可以说:
Box<Cat> is subtype of Box<? extends Animal>
实际上:我什至不确定是否 Box<? extends Animal>
和? extends Animal
是类型
最佳答案
Given a generic type declaration
C<F1,...,Fn>
(n > 0), the direct supertypes of the parameterized typeC<T1,...,Tn>
, whereTi (1 ≤ i ≤ n)
is a type, are all of the following:
- [...]
C<S1,...,Sn>
, whereSi
containsTi (1 ≤ i ≤ n)
(§4.5.1).
和about containing described above
A type argument
T1
is said to contain another type argumentT2
, writtenT2 <= T1
, if the set of types denoted byT2
is provably a subset of the set of types denoted byT1
under the reflexive and transitive closure of the following rules (where<:
denotes subtyping (§4.10)):? extends T <= ? extends S if T <: S ? extends T <= ? T <= T T <= ? extends T [...] // see these if you are interested
就你而言,
Box<Cat>
我们关心Cat
。综上所述,我们可以说? extends Cat
包含Cat
。然后我们可以说? extends Animal
包含? extends Cat
,自 Cat <: Animal
。所以? extends Animal
包含Cat
。因此Box<? extends Animal>
是参数化类型 Box<Cat>
的直接父类(super class)型
因此,Box<Cat>
是 Box<? extends Animal>
的子类型.
关于java - `Box<Cat>` 是 `Box<? extends Animal>` 的子类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24397112/