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

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

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+"个对象");
	}
}

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

猜你喜欢

转载自www.cnblogs.com/xp-thebest/p/11704175.html