计算建立对象的个数

1、程序设计思想

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

2、程序源代码

class sum{

public static int a=0;
int b;
public sum(int b1)
{
b=b1;
a++;
}

public int get()
{
return a;
}

}

public class Ccj{

public static void main(String[] args) {

sum o1=new sum(1);
sum o2=new sum(2);
sum o3=new sum(3);

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

   }

}

3、运行截图

原文地址:https://www.cnblogs.com/3066405538a/p/4888450.html