99

我在 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假设空检查未初始化的对象是准确的?

4

2 回答 2

121

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.

于 2013-05-22T18:59:31.430 回答
16

如果Object引用已声明但未实例化,则其值为null.

于 2013-05-22T18:59:38.727 回答