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

源代码:

public class test {
 public static void main(String[] args) {
  test t1=new test();
  test t2=new test();
  test t3=new test();
  test t4=new test();
  System.out.println("一个创建了"+n+"个对象");
 }
 static int n=0;
 public test() {
  n++;
 }
}

 

测试截图

 

posted @ 2019-10-17 16:35  .HAHA  阅读(185)  评论(0编辑  收藏  举报