创建一个静态变量,每生成一个对象,使该变量加一
package trackobjectnum; public class ObjectNum { private static int n = 0; public ObjectNum() { n = n + 1; } public static int getNum() { return n; } public static void main(String[] args) { ObjectNum o1 = new ObjectNum(); ObjectNum o2 = new ObjectNum(); ObjectNum o3 = new ObjectNum(); ObjectNum o4 = new ObjectNum(); System.out.println("已生成对象个数为:" + ObjectNum.getNum()); } }
运行结果