使用类的静态字段和构造函数,可以跟踪某个类所创建对象的个数。

package test1021;

public class qwq {
    private static int n = 0;
    public qwq() {
        n += 1;
    }
    public static int getNumber() {
        return n;
    }
    
    public static void main(String[] args) {
        qwq q1 = new qwq();
        qwq q2 = new qwq();
        qwq q3 = new qwq();
        qwq q4 = new qwq();
        System.out.println("已生成对象个数为:" + qwq.getNumber());
    }
}

运行结果为:4.

原文地址:https://www.cnblogs.com/jmdd/p/9827394.html