1、程序设计思想

定义一个静态字段,在构造函数中写一个这个静态字段自加的语句,这样,因为静态字段不会因为再次调用而改变数值所以可以计算建立对象的个数。

2、程序源代码

//使用类的静态字段和构造函数跟踪对象

class sum{

    public static int a=0;

    int c;  

    public sum(int cc)

    {

       c=cc;

       a++;

    }

    public int get()

    {

       return a;

    }

}

public class WyText_LL3 {

   public static void main(String[] args) {  

     // TODO Auto-generated method stub   

    //调用

      sum one=new sum(2);

        sum two=new sum(3);   

    sum three=new sum(3);   

    //输出   

    System.out.println(one.get());

   }

}

3、运行截图