题目要求:使用类的静态字段和构造函数,可以跟踪某个类所创建对象的个数。请写一个类,在任何时候都可以向它查询“你已经创建了多少个对象?”。
import java.util.Scanner; //跟踪某个类所创建对象的个数 public class countClass { static int count = 0; public countClass() { } public static void main(String args[]) { Scanner sc = new Scanner(System.in); int i; do { System.out.println("是否创建对象:是:1 否:其他"); i = sc.nextInt(); if (i == 1) { new countClass(); countClass.count++; System.out.println("您一共创建了" + countClass.count + "个对象"); } else {i = 0; System.out.println("是否继续创建对象:是:1 否:其他");} } while (i != 0); } }
结果截图:
原文:https://www.cnblogs.com/ywqtro/p/11686047.html