深入理解java中的null“類型”,深入理解null

來源:互聯網
上載者:User

深入理解java中的null“類型”,深入理解null

本文研究的主要是java中的null“類型”的相關執行個體,具體介紹如下。

先給出一道簡單的null相關的題目,引發我們對null的探討,後面會根據官方語言手冊對null“類型”進行解讀。

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

解析:

輸出應該為 :haha

因為null 是可以強轉為任何類類型的,所以前面((NULL)null)是合法的,但是null強轉以後是無效對象,其傳回值為null,(後面會作解釋)

而haha方法是靜態方法,靜態方法使用靜態繫結,不會拋出null 指標異常。

如果把haha()函數變為非靜態之後,將會拋出null 指標異常。

再來一個例子:

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

結果還是輸出“haha”

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 參考(其實還是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可以被轉換為任何參考型別。”

通過官方的語言手冊,對null類型有了非常深刻的理解。

對我們編程以及以後求職筆試面試都有一定的協助。

最後希望大家遇到一些奇怪的問題,除了百度外,盡量多去Stack Overflow網站上去搜尋,也多去查官方手冊。

總結

以上就是本文關於深入理解java中的null“類型”的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.