使用 'new' 的构造函数与使用 'this()' 的构造函数有何不同?

How does a constructor with 'new' differ from a constructor using 'this()'?

在学习 Java OCA 考试时,我发现很难理解使用 this() 和使用 [=19= 链接构造函数之间的区别]新。 示例:

public class BirdSeed {
    private int numberBags;

    public BirdSeed(){           
        this(2);                 //  but why not use 'new BirdSeed(2);' instead of 'this(2)' ?
    } 

    public BirdSeed(int numberBags){
        this.numberBags = numberBags;
    }

    public static void main(String[] args) {
        BirdSeed seed = new BirdSeed();
        System.out.println(seed.numberBags);
    }

}

但为什么不使用 new BirdSeed(2);,如单行注释中所建议的,因为这将调用构造函数并创建一个新对象。

那么,根据上述上下文,'this()' 和 'new' 有何不同?

因为new BirdSeed(2)创建了一个new(完全不相关的)对象,而this(2)在当前对象上调用相应的构造函数。

But why not use new BirdSeed(2);, as suggested in the single-line comment, since this will call the constructor and create a new object

如果你写 new BirdSeed(2),你将创建 BirdSeed 的第二个实例(除了执行 BirdSeed() 构造函数的原始实例之外),你赢了' 为原始 BirdSeed 实例执行 BirdSeed(int numberBags) 构造函数的主体。

另一方面,调用 this(2) 执行原始实例的 BirdSeed(int numberBags) 构造函数体。

你可以先让自己相信其中的区别 运行:

public BirdSeed(){           
    this(2); 
    System.out.println(numberBags);       // prints 2
} 

然后 运行:

public BirdSeed(){           
    new BirdSeed(2); 
    System.out.println(numberBags);       // prints 0
} 

您还可以使用以下代码观察不同的行为:

public BirdSeed(){           
    BirdSeed other = new BirdSeed(2); 
    System.out.println(this == other);       // prints false
}

如您所见,执行 BirdSeed(int numberBags) 构造函数的实例与执行 BirdSeed() 构造函数的实例不同。

你也可以用new BirdSeed(2),完全有效。 this() 语法的原因是当你想要初始化一个没有任何参数的 class 时,numberBags 的默认值是使用 this() 语法为你初始化的,它只是为你调用 BirdSeed(2) (然而它调用了那个构造函数但它没有创建 BirdSeed 的新实例)。