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

}
public class Test {
    private static int n = 0;
    public Test() {
        n++;
    }
    public static int getNum() {
        return n;
    }
    
    public static void main(String[] args) {
     Test t1 = new Test();
     Test t2 = new Test();
     Test t3 = new Test();
        System.out.println("已生成对象个数为:" + Test.getNum());
    }
}
posted @ 2019-10-18 17:36  明月照我还  阅读(109)  评论(0编辑  收藏  举报