请写一个java类,在任何时候都可以向它查询“你已经创建了多少个对象?”

这个问题解决方法很简单,只要设置一个类的静态整型成员(事例中我设置的是n),初始化值为1,然后在其构造函数中添加语句使其+1(n++),这样需要查询创建了多少个对象时直接查询n的值就可以了,如下:

 1 package trr;
 2 
 3 public class trr
 4 {
 5     public static void main(String[] args) 
 6     {
 7         a c1=new a();
 8         System.out.println("创建了"+a.n+"个对象");
 9         a c2=new a();
10         System.out.println("创建了"+a.n+"个对象");
11         a c3=new a();
12         System.out.println("创建了"+a.n+"个对象");
13         a c4=new a();
14         System.out.println("创建了"+a.n+"个对象");
15     }
16 }
17 class a
18 {
19     static int n=0;//设置静态成员
20     
21     public a() 
22     {
23         n++;//使得n在创建对象时+1
24     
25     }
26 
27 
28 }

运行结果如下:

原文地址:https://www.cnblogs.com/liuleliu/p/11693082.html