未初始化的对象与初始化为 NULL 的对象 [英] Uninitialized Object vs Object Initialized to NULL
问题描述
我在 Java 工作.
I'm working in Java.
我通常这样设置一些对象:
I commonly setup some objects as such:
public class Foo {
private SomeObject someName;
// do stuff
public void someMethod() {
if (this.someName != null) {
// do some stuff
}
}
}
问题是:这个例子中的someName
是否等同于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屋!