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.
class Test {
static int noOfObjects = 0 ;
{
noOfObjects += 1 ;
}
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" );
System.out.println(Test.noOfObjects);
}
}
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 Oct, 2019
Like Article
Save Article