Java 计算创建的类对象的数量
我们的想法是使用类中的静态成员来计算对象。一个静态成员被类中的所有对象共享,如果没有其他初始化,所有的静态数据在第一个对象被创建时被初始化为零,而且构造函数和静态成员函数只能访问静态数据成员、其他静态成员函数和类外的任何其他函数。
我们创建了一个静态int类型的变量,并把这个静态变量加上一个增量运算符,使其在构造函数中增加1。
// Java program Find Out the Number of Objects Created
// of a Class
class Test {
static int noOfObjects = 0;
// Instead of performing increment in the constructor
// instance block is preferred to make this program generic.
{
noOfObjects += 1;
}
// various types of constructors
// that can create objects
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("GFG");
// We can also write t1.noOfObjects or
// t2.noOfObjects or t3.noOfObjects
System.out.println(Test.noOfObjects);
}
}
输出:
3