溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2021-01-16 10:15:42 來源:億速云 閱讀:307 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關(guān)java中null“類型”的作用是什么,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

題目:下面程序能正確運行嗎?

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

解析:

輸出應(yīng)該為 :haha

因為null 是可以強(qiáng)轉(zhuǎn)為任何類類型的,所以前面((NULL)null)是合法的,但是null強(qiáng)轉(zhuǎn)以后是無效對象,其返回值為null,(后面會作解釋)

而haha方法是靜態(tài)方法,靜態(tài)方法使用靜態(tài)綁定,不會拋出空指針異常。

如果把haha()函數(shù)變?yōu)榉庆o態(tài)之后,將會拋出空指針異常。

再來一個例子:

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

這道題其實和上面是差不多的。

結(jié)果還是輸出“haha”

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

Java Language Specification中我們可以看到

在4.1. The Kinds of Types and Values一節(jié)中提到:

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類型即表達(dá)式null的類型,它沒有名字。

因為null類型沒有名字,所以不可能聲明為null類型的變量或者轉(zhuǎn)換為null類型。

null引用是null類型表達(dá)式唯一可能的值。

null引用可以轉(zhuǎn)換為任意引用類型。

實際上,程序員可以忽略null類型,可以認(rèn)為null僅僅是一個可以成為任何引用類型的特殊符號。

看了這個一段,就比較豁然開朗了。

在5.2. Assignment Conversion一節(jié)中:

“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這一節(jié)有:

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

即“null可以被轉(zhuǎn)換為任何引用類型?!?/p>

看完上述內(nèi)容,你們對java中null“類型”的作用是什么有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI