加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

难以理解Java规范

发布时间:2020-12-15 03:05:05 所属栏目:Java 来源:网络整理
导读:阅读 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. 我一直在寻
阅读 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<:T:S:> T,即一个类必须继承另一个类;否则会出现编译时错误.所以你的基本设置如下:
class T {
}
class S extends T {
}

到目前为止一直很好:允许你将S转换为T,因为这两个类之间存在适当的子类关系.

现在让我们看看条件的第二部分:两个类必须具有不同的超类型.由于只允许一个超类,因此常见的超类需要是一个接口.以下是如何打破规则的第二部分的一个示例:

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

X和Y的擦除需要实现List< ???>,但是列表必须在不同类型上参数化.这会导致编译时错误,因为S无法同时满足List< String>和列表<整数>接口.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读