【发布时间】:2020-11-05 23:45:47
【问题描述】:
愚蠢的问题,但有人可以向我解释为什么下面的代码计算事物对象的数量吗?我不明白为什么定义的计数方法会计算对象的数量?迭代什么时候开始?任何有关澄清的帮助将不胜感激
class Thing {
public String name;
public static int count = 0;
public Thing() {
id = count;
count++;
}
public void showName() {
System.out.println("Object ID: " + id + ", " + description + ": " + name);
}
}
public class Java_Static {
public static void main(String[] args) {
// using count method
System.out.println("Before creating objects, count is: " + Thing.count);
// using variable
Thing thing1 = new Thing();
Thing thing2 = new Thing();
thing1.name = "Abid";
thing2.name = "Ruksaar";
thing1.showName();
thing2.showName();
System.out.println("After creating objects, count is: " + Thing.count);
}
}
【问题讨论】:
-
没有count方法,只是一个字段,基本上是一个在构造函数中递增的全局变量。
-
请注意,使用可修改的类字段(而不是实例字段)被认为是代码异味。相反,您可以使用工厂模式,例如,工厂保持计数。
-
每创建一个Thing对象,静态变量Thing.count就会增加。