Подсчет количества объектов класса
Создал статическое поле boxCount и конструктор в классе Box. Сделал вывод в классе Main, но почему-то результат - число 0. Хотя создано 3 объекта. В чем может быть проблема?
public class Main {
public static void main(String[] args) {
System.out.println("Кол-во коробок = " + Box.getBoxCount());
Box firstBox = new Box(0.2, 1.4, 2.4);
Box secondBox = new Box(2.3, 0.8, 3.2);
Box thirdBox = new Box(1.3, 0.6, 1.2);
}
}
public class Box {
private static int boxCount;
private double width;
private double height;
private double depth;
public Box() {
boxCount++;
}
public static int getBoxCount() {
return boxCount;
}
public Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
}
Ответы (1 шт):
Автор решения: Igor
→ Ссылка
public Box(double width, double height, double depth) {
this(); // !!!
this.width = width;
this.height = height;
this.depth = depth;
}
Это называется constructor chaining.