gpt4 book ai didi

java - 难以理解 Java 规范的条件

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:32:03 24 4
gpt4 key购买 nike

在阅读 Java 的 SE 规范中的引用类型转换时:

Given a compile-time reference type S (source) and a compile-time reference type T (target), a casting conversion exists from S to T if no compile-time errors occur due to the following rules.

我不断发现以下情况:

If S is a class type: If T is a class type, then either |S| <: |T|, or |T| <: |S|. Otherwise, a compile-time error occurs.

Furthermore, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types (§4.5), and that the erasures of X and Y are the same, a compile-time error occurs.

任何人都可以给我一个这种情况的例子吗?

编辑:

有关我引用的文章的进一步说明,请参阅有关此 link 的第 5.5.1 节

最佳答案

条件的第一部分要求 S <: TS :> T ,即一个类必须继承自另一个类;否则会出现编译时错误。所以您的基本设置如下所示:

class T {
}
class S extends T {
}

到目前为止一切顺利:您可以使用 ST , 因为这两个类之间存在适当的子类关系。

现在让我们看一下条件的第二部分:两个类必须有不同的父类(super class)型。由于只允许一个父类(super class),因此公共(public)父类(super class)型需要是一个接口(interface)。下面是一个如何打破规则第二部分的例子:

// X is List<String>
class T implements List<String> {
}
// Y is List<Integer>
class S extends T implements List<Integer> {
}

删除 XY需要实现List<???> ,但列表必须在不同类型上进行参数化。这会导致编译时错误,因为 S无法同时满足 List<String>List<Integer>接口(interface)。

关于java - 难以理解 Java 规范的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32383174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com