未初始化对象与初始化为 NULL 的对象

我在 Java 工作。

我通常设置一些对象如下:

public class Foo {
private SomeObject someName;


// do stuff


public void someMethod() {
if (this.someName != null) {
// do some stuff
}
}
}

问题是: 在这个例子中 someName是否等同于 null,因为在我可以 reliably for all objects假设空检查未初始化的对象将是准确的?

104723 次浏览

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.

From the Java Language Specification, section 4.12.5:

Initial Values of Variables

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

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

If an Object reference has been declared but not instantiated, its value is null.