使用 null 或默认构造函数初始化对象之间的区别

the difference between initialize an object with null or it's default constructor

假设我们有一个Class并且它只包含一个实例变量并且它的类型是引用类型。我们没有实现任何构造函数,所以 Class 有它的默认构造函数。

如果我没理解错的话,默认构造函数给实例变量一个默认值,而引用类型的默认值为null。是真的吗?

如果是,我们要为这个class创建一个对象。声明和初始化 this Class 的对象的这两个语句之间有什么区别吗?

Class object = null;

Class object = new Class();

Is there any difference between these two statements for declare and initialize an object of this class???

Class object = null;

and

Class object = new Class();

第一个初始化class的一个对象,它只是声明一个变量并给它赋值null。没有实例,所以没有实例字段。

第二个初始化 class 的一个实例,因此初始化它拥有的任何实例字段。如果这些字段中的任何一个是引用,并且您还没有实现构造函数,它们将被初始化为 null.

让我们用一个具体的例子:

class Foo {
    String str;
}

由于str是引用,如果我们创建Foo的实例,str将被初始化为null

你的第一个语句(更改 Class => Fooobject => f 以避免混淆):

Foo f = null;

...内存中的结果:

+----------------+
| f (a variable) |
+----------------+
| null           |
+----------------+

你的第二个陈述:

Foo f = new Foo();

...给了我们一些非常不同的东西:

+----------------+
| f (a variable) |
+----------------+     +--------------+
| (ref #412785)  |---->| Foo instance |
+----------------+     +--------------+
                       | str: null    |
                       +--------------+