[英]Why can we instantiate multiple variables at once?
在最近的項目中追蹤了一些NullPointerException
之后,我終於找到了它們的來源,這讓我感到驚訝。 盡管我現在可以准確地描述它們的來源以及如何防止它們,但我仍然對如何允許這種行為而無需編譯器或至少IDE發出警告感到困惑。
我瀏覽了Stack並進行了相當廣泛的谷歌搜索,但是找不到關於此的任何內容。 順帶一提,這里有一些代碼演示了這種奇怪的行為。
public class Test {
String what, why, where = "who knows?";
public static void main(String[] args) {
System.out.println("The 'what' String = " +new Test().what);
}
}
輸出;
The 'what' String = null
如果分別聲明和實例化每個String,這將顯示正確的輸出,但是像這樣將它們鏈接在一起會導致它們實例化為null
。 那么,問題是為什么呢? 如果這是標准行為,那么為什么編譯器甚至允許我們以這種方式實例化String
對象?
因為在內部它可以歸結為:
String what=null;
String why = null;
String where="who knows?"; // declaring 2 strings, only assigning the value to the third one.
String what, why, where = "who knows?";
僅為where
變量設置值,而其他設置為默認值,即為null
(當然,如果它們是類成員)。
您可以執行以下操作:(假設您希望它們都具有相同的值):
String what, why, where;
what = why = where = "who knows?"
請注意,這兩個語句應位於方法,構造函數或(靜態)初始化器中。
那等於跟隨,只有where
將其初始化為給定值"who knows?"
,其他設置為默認值null
String what;
String why;
String where="who knows?";
嘗試
String what, why, where;
what = why = where = "who knows?";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.