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

 1 import java.util.Scanner;
 2 
 3 class Number{   //静态方法计数
 4     static int number=0;
 5     static void show() {
 6         ++number;  //计数器
 7         System.out.println("目前创建了"+number+"个对象");
 8     }
 9 }
10 
11 
12 
13 public class Test4 {
14      
15     public static void main(String[] args) {
16         Scanner sc=new Scanner(System.in);
17         int a=1;
18         while(a!=0) {
19             Number n=new Number();
20             n.show();
21             System.out.println("是否继续创建?1 创建 0 停止创建");
22             a=sc.nextInt();
23         }
24 }
25 }

运行示例:

目前创建了1个对象
是否继续创建?1 创建 0 停止创建
1
目前创建了2个对象
是否继续创建?1 创建 0 停止创建
0

设计思路:

创建一个int 型变量,为静态变量,记录创建的次数,调用构造方法的同时记录创造次数,同时输出结果。

原文地址:https://www.cnblogs.com/cxy0210/p/11685709.html