[英]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.