我看到有些人在这里的第二个构造做的东西,如:Java:通过构造函数调用构造函数,有什么意义?
public class Apples {
String color;
int quantity;
public Apples(String color, int quantity) {
this.color = color;
this.quantity = quantity;
}
public Apples(String color) {
this(color, 0);
}
}
什么是这样做的原因是什么?对我来说,似乎你正在调用一个额外的方法(构造函数),只是为了节省几行。我回想几年前一位教授说这是不好的做法,但我不记得他这样说的原因。
其原因是您可以使用相同的代码并在较小的构造函数中使用“默认”值。没有代码重复。 – pL4Gu33
这是肯定的*不*不好的做法。 – qqilihq
这是**最佳实践**,因为您将构造函数逻辑委托给单一方法。为什么你应该这样做有几个原因。将尝试找到一些关于它的文章... –