10-21跟踪类对象

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


package
main; public class Obj { public static void main(String[] args) { New a = new New(); System.out.println(a); New b = new New(); System.out.println(b); New c = new New();//三个对象 System.out.println(c); New.Count();//输出数量 } } class New{ static int n ; New(){ n+=1; //每定义一个对象,n+1 } static void Count(){ System.out.println(n); //输出静态变量 } }

 

posted @ 2018-10-21 15:33  fsdx  阅读(79)  评论(0编辑  收藏  举报