你已经创建了多少个对象?

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package ppt_test;
public class test4 {
    int value;
    static int a=0;
    test4(){
        a++;
    }
    public static void main(String args[])
    {
            test4 a=new test4();
            test4 b=new test4();
            System.out.println("你已经创建了"+a.a+"个对象");
    }
}

 

        实现这个很简单只需要在类中定义一个静态变量,在构造函数中实现对变量的累加,然后在主函数中输出即可。

 

posted @   xppp11  阅读(241)  评论(0)    收藏  举报
点击右上角即可分享
微信分享提示