//使用类的静态字段和构造函数,可以跟踪某个类所创建对象的个数。
1 package demo; 2 3 //import java.util.Scanner; 4 5 public class Num_Obj { 6 7 8 static private int num = 0; 9 10 Num_Obj() 11 { 12 num ++ ; 13 } 14 15 public int getNum() { 16 return num; 17 } 18 19 20 21 public static void main(String[] args) { 22 // TODO Auto-generated method stub 23 24 Num_Obj o1 = new Num_Obj(); 25 System.out.println("创建的第" + o1.getNum() + "个对象"); 26 27 28 for(int k = 0; k < 10; k++) 29 { 30 Num_Obj obj= new Num_Obj(); 31 //obj = new Num_Obj(); 32 System.out.println("创建对象个数:" + obj.getNum()); 33 } 34 35 } 36 37 }