未初始化的对象与对象初始化为NULL [英] Uninitialized Object vs Object Initialized to NULL
问题描述
我在Java工作。
我经常设置一些对象:
public class Foo {
private SomeObject someName;
// do stuff
public void someMethod() {
if (this.someName != null) {
// do some stuff
}
}
}
问题是:<$这个例子中的c $ c> someName 等同于 null
,因为我可以可靠地为所有对象
假设null检查未初始化的对象是否准确?
The question is: Is someName
in this example equated to null
, as-in I can reliably for all objects
assume null-checking uninitialized objects will be accurate?
推荐答案
正确,引用类型的静态和实例成员都不是显式初始化由Java设置为 null
。同样的规则适用于数组成员。
Correct, both static and instance members of reference type not explicitly initialized are set to null
by Java. The same rule applies to array members.
来自 Java语言规范,第4.12.5节:
From the Java Language Specification, section 4.12.5:
变量的初始值
程序中的每个变量在使用其值之前必须具有一个值:
Every variable in a program must have a value before its value is used:
每个类变量,实例变量,或者数组组件在创建时使用
默认值初始化
Each class variable, instance variable, or array component is initialized with a default value when it is created
[...]对于所有引用类型,默认值为 null
。
[...] For all reference types, the default value is null
.
请注意,上述规则排除了局部变量:必须明确初始化它们,否则程序将无法编译。
Note that the above rule excludes local variables: they must be initialized explicitly, otherwise the program will not compile.
这篇关于未初始化的对象与对象初始化为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!