Saturday, October 11, 2025
HomeLanguagesJavaCount number of a class objects created in Java

Count number of a class objects created in Java

The idea is to use static member in the class to count objects. A static member is shared by all objects of the class, all static data is initialized to zero when the first object is created if no other initialization is present, And constructor and static member function can only access static data member, other static member functions and any other functions from outside the class.

We create a static int type variable and put this a static variable with an increment operator so that it increases by 1 in the constructor.




// 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);
    }
}


Output:

3
RELATED ARTICLES

Most Popular

Dominic
32350 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6720 POSTS0 COMMENTS
Nicole Veronica
11882 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6839 POSTS0 COMMENTS
Ted Musemwa
7102 POSTS0 COMMENTS
Thapelo Manthata
6794 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS