java - `Box<Cat>` 是 `Box<? extends Animal>` 的子类型吗?

标签 java generics type-systems

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是类型

最佳答案

Java Language Specification

Given a generic type declaration C<F1,...,Fn> (n > 0), the direct supertypes of the parameterized type C<T1,...,Tn>, where Ti (1 ≤ i ≤ n) is a type, are all of the following:

  • [...]
  • C<S1,...,Sn>, where Sicontains Ti (1 ≤ i ≤ n) (§4.5.1).

about containing described above

A type argument T1 is said to contain another type argument T2, written T2 <= T1, if the set of types denoted by T2 is provably a subset of the set of types denoted by T1 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/

相关文章:

java - 从 EJB 创建文本文件,无需 java.io

java - 应用程序日志未刷新

java - 检查一个 java.lang.reflect.Type 的对象是否可以转换为另一个的组件?

c# - 为什么我们*应该*使用 EventHandler

scala - Scala 中具有 F 界类型和存在类型的编译问题

java - 如何为 "virtual files"列表创建 ZIP 文件并输出到 httpservletresponse

Java8 : ambiguity with lambdas and overloaded methods

language-agnostic - 编码为通用时编码与使用存在类型

haskell - Milner 是否让多态性成为 2 级特征?

java - Java PERM 生成在哪里?