本文研究的主要是java中的null“類型”的相關實例,具體介紹如下。
先給出一道簡單的null相關的題目,引發我們對null的探討,后面會根據官方語言手冊對null“類型”進行解讀。
題目:下面程序能正確運行嗎?
解析:
輸出應該為 :haha
因為null 是可以強轉為任何類類型的,所以前面((null)null)是合法的,但是null強轉以后是無效對象,其返回值為null,(后面會作解釋)
而haha方法是靜態方法,靜態方法使用靜態綁定,不會拋出空指針異常。
如果把haha()函數變為非靜態之后,將會拋出空指針異常。
再來一個例子:
這道題其實和上面是差不多的。
結果還是輸出“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)。
在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“類型”的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/w605283073/article/details/72896651