为什么 null 被称为“每个引用类型的子类型”?
伙计们,有人可以对我在这本书中遇到的短语给出一个合乎逻辑的解释吗? :
您可能会发现思考
有帮助吗?将 T
扩展为包含由下面的null
类型和上面的T
类型界定的区间内的每个类型(其中null 的类型
是每个引用类型的子类型)。
谢谢。
Guys, could any one give a logical explanation of phrase I met in this book:
You may find it helpful to think of
? extends T
as containing every type in an interval bounded by the type ofnull
below and byT
above (where the type ofnull
is a subtype of every reference type).
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为这只是意味着您可以将空引用分配给任何引用类型。在我看来,这并不是一种非常有帮助的思考方式。
Java 语言规范对 null 类型有这样的说法(在 第 4.1 节):
I think it just means that you can assign the null reference to any reference type. It doesn't strike me as a terribly helpful way of thinking about it.
The Java Language Specification has this to say about the null type (in section 4.1):
类型形成偏序,即对于程序中所有类型集合中的任何两个类型,它们之间可能存在关系(即 T1 < T2 - T2 在某些情况下是 T1 的子类型)感觉)。不相关的类层次结构中的事物没有定义这种关系。
基本上,这告诉您的是
类型集的所有成员? extends T
描述小于T
且大于null
。 null 作为所有内容的子类型存在,因为将值null
分配给引用始终有效。更正式地说:
Types form a partial order, i.e. for any two types in the set of all types in the program, there might be a relation between them (i.e.
T1 < T2
- T2 is a subtype of T1 in some sense). Things in unrelated class hierarchies have no such relation defined.So basically what this is telling you is that all members of the set of types that
? extends T
describes is less thanT
and greater thannull
. null exists as a subtype of everything because it is always valid to assign the valuenull
to a reference.More formally:
摘自这篇有趣的文章:
From this interesting article, an excerpt:
这意味着 null 可以是任何类型。
您可能有一个类
Animal
和一个子类Dog
。如果您有一个
Animal
类型的变量,其值为null
,您无法判断null
是否属于Animal
类型> 或输入Dog
。两者同样有效。That means that null can be any type.
You might have a class
Animal
with a subclassDog
.If you have a variable of type
Animal
with the valuenull
you can not tell if thenull
is of typeAnimal
or typeDog
. Both are equally valid.对于任何类型 T 都成立。
is true for any type T.