+ 2

How can I code to print out how many objects are made of a class?

25th Apr 2020, 9:41 PM
Donya
Donya - avatar
2 ответов
+ 7
Hi Donya a simple solution would be to declare a static variable in the class. You can increment it inside the constructor you are using to create an object. It could be either a default or parametrized constructor. So the static variable will keep count of the number of objects created of that class and you can call it at the end of your code to return the answer.
25th Apr 2020, 9:50 PM
Avinesh
Avinesh - avatar
+ 2
//Code Example: class Program { static int objcount=0; Program() { objcount++; } public static void main(String args[]) { Program a1=new Program(); Program a2=new Program(); Program a3=new Program(); System.out.println( "No.of objects made :" + Program.objcount ); } }
25th Apr 2020, 10:15 PM
Jayakrishna 🇮🇳