Yes, we can count the number of objects created of a class in
java. To understand this please sees the example below.
Example:-
package demo;
public class TestDemo {
static int count=0;
TestDemo()
{
count=++count;
}
public static void main(String args[])
{
TestDemo obj1 = new TestDemo();
TestDemo obj2 = new TestDemo();
TestDemo obj3 = new TestDemo();
TestDemo obj4 = new TestDemo();
System.out.println(“You have created ”+count+” times the object for TestDemo class.”);
}
}
public class TestDemo {
static int count=0;
TestDemo()
{
count=++count;
}
public static void main(String args[])
{
TestDemo obj1 = new TestDemo();
TestDemo obj2 = new TestDemo();
TestDemo obj3 = new TestDemo();
TestDemo obj4 = new TestDemo();
System.out.println(“You have created ”+count+” times the object for TestDemo class.”);
}
}
Output of the above program is: [You have created 4 times
the object for TestDemo class.]
As we all know that the execution of java program starts from the
main method of the public class and whenever an object of the class is created,
its constructor will be called automatically.
In the above example we created a class TestDemo and defined the TestDemo() constructer having logic for incrementing
the integer type count variable by value one(1) also for the class. After this
when we created the object of the TestDemo class in the main method with the
blank constructor, the TestDemo() constructor called automatically and incremented
the count variable by 1. Similarly, we created the object of the class TestDemo
four times in the above example and TestDemo() constructor was also called for
four times automatically and hence it incremented the integer type count
variable’s (declared and defined in the TestDemo class) value by 4 that’s why the result was showing 4.
So every time a new object for the class TestDemo will be created,
the TestDemo() constructor will be run once for the every object creation and will
increment the count variable value by one. So the count variable value will
always be equal to the number of object created for the class TestDemo and we
can check this by printing the value of count variable at the end of the
program.
No comments:
Post a Comment