计算已经创建了多少个对象

1.程序设计思路:

  使用类的静态变量统计对象个数,类的构造函数中使变量自增1。当每创建一个类对象时,静态变量加1。

2.实验代码:

 1 public class B {
 2     static int sum = 0;//保存当前已创建对象个数
 3     public static void main(String[] args) {
 4         B b1 = new B();
 5         B b2 = new B();
 6         B b3 = b2;
 7         System.out.println(B.sum);
 8     }
 9     public static int getSum(){
10         return sum;
11     }
12     public B(){
13         sum++;
14     }
15 }

3.执行结果:

  

posted @ 2017-10-20 07:29  ╄冷丶夜♂  阅读(227)  评论(0编辑  收藏  举报