利用静态变量记录创建的实例的个数

使用类的静态字段和构造函数,我们可以跟踪某个类所创建对象的个数。请写一个类,在任何时候都可以向它查询“你已经创建了多少个对象?

 1 public class Test2 {
 2       private static int num = 0;
 3       private int value = 100;
 4       public Test2() {
 5           num++;
 6       }
 7       public Test2(int value) {
 8           this.value = value;
 9           num++;
10       }
11       public static void Count() {
12           System.out.println("当前创建的实例对象有"+num+"个");
13       }
14       public static void main(String[]args) {
15           Test2 t1 = new Test2();
16           Test2 t2 = new Test2();
17           Test2 t3 = new Test2();
18           Test2.Count();
19           Test2 t4 = new Test2(300);
20           Test2 t5 = new Test2(250);
21           Test2.Count();
22       }
23 }

原文地址:https://www.cnblogs.com/messi2017/p/7684019.html