标签:
使用类的静态字段和构造函数,我们可以跟踪某个类所创建对象的个数。请写一个类,在任何时候都可以向他查询“你已经创建了几个对象”
源代码:
package Statistics; public class Statistics { private static int n; public Statistics() { n++; //每次new一个对象是n+1 } public static int getNum() { return n; } public static void main(String[] args){ Statistics s1=new Statistics(); Statistics s2=new Statistics(); Statistics s3=new Statistics(); Statistics s4=new Statistics(); Statistics s5=new Statistics(); Statistics s6=new Statistics();//创建对象昂 System.out.println("已经创建的对象个数为:"+Statistics.getNum()); } }
截图:
标签:
原文地址:http://www.cnblogs.com/hongniuke/p/4887360.html