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

 

public class Student{

public static void main(String[] args){

Information a = new Information();

a.OutputInformation();

Information b = new Information();

b.OutputInformation();

} }

class Information{

static int num=0;

Information()

{ num++;

}

public void OutputInformation()

 {

System.out.println("你已经创建了"+num+"个对象!");

}

}