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 initialize 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;
  
    // non-parameterized constructor. Unlike other non-static
    // functions, a constructor can access static members
    public Test()
    {
        noOfObjects += 1;
    }
  
    public static void main(String args[])
    {
       Test t1 = new Test();
       Test t2 = new Test();
       Test t3 = new Test();
  
       // We can also write t1.noOfObjects or
       // t2.noOfObjects or t3.noOfObjects
       System.out.println(Test.noOfObjects);
    }
}

Output:

3


My Personal Notes arrow_drop_up

Strategy Path planning and Destination matters in success No need to worry about in between temporary failures

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.