资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

java中null“类型”的作用是什么

今天就跟大家聊聊有关java中null“类型”的作用是什么,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

创新互联公司专注于江阳企业网站建设,成都响应式网站建设,商城网站制作。江阳网站建设公司,为江阳等地区提供建站服务。全流程按需定制制作,专业设计,全程项目跟踪,创新互联公司专业和态度为您提供的服务

题目:下面程序能正确运行吗?

java中null“类型”的作用是什么

解析:

输出应该为 :haha

因为null 是可以强转为任何类类型的,所以前面((NULL)null)是合法的,但是null强转以后是无效对象,其返回值为null,(后面会作解释)

而haha方法是静态方法,静态方法使用静态绑定,不会抛出空指针异常。

如果把haha()函数变为非静态之后,将会抛出空指针异常。

再来一个例子:

java中null“类型”的作用是什么

这道题其实和上面是差不多的。

结果还是输出“haha”

java中null“类型”的作用是什么

Java Language Specification中我们可以看到

在4.1. The Kinds of Types and Values一节中提到:

There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). ”
Type:
PrimitiveType
ReferenceType
There is also aspecial null type, the type of the expression null (§3.10.7, §15.8.1), which has no name.
Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type.
The null reference is the only possible value of an expression of null type.
The null reference can always undergo a widening reference conversion to any reference type.
In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

我给翻译一下:

Java语言中有两种类型,一种是基本类型,还有一种是引用类型

还有一个特殊的null类型即表达式null的类型,它没有名字。

因为null类型没有名字,所以不可能声明为null类型的变量或者转换为null类型。

null引用是null类型表达式唯一可能的值。

null引用可以转换为任意引用类型。

实际上,程序员可以忽略null类型,可以认为null仅仅是一个可以成为任何引用类型的特殊符号。

看了这个一段,就比较豁然开朗了。

在5.2. Assignment Conversion一节中:

“A value of the null type (the null reference is the only such value) may be assigned to any reference type, resulting in a null reference of that type”

一个null类型(null(空)引用是这种类型的唯一的一个值)的值,可以赋值给任意类型,将返回一个该类型对象的空引用(其实还是null)。

在5.3. Method Invocation Conversion这一节有:

“A value of the null type (the null reference is the only such value) may be converted to any reference type.”

即“null可以被转换为任何引用类型。”

看完上述内容,你们对java中null“类型”的作用是什么有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。


分享文章:java中null“类型”的作用是什么
路径分享:http://cdkjz.cn/article/gggphh.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220