Java Program to Count Number of Objects Created for Class

This is a Java Program to Find Out the Number of Objects Created of a Class.

Whenever an object is made of a class, its constructor is invoked. Whenever the constructor runs we increment the counter value. Hence number of objects created of a class equals to the counter value.

Here is the source code of the Java Program to Find Out the Number of Objects Created of a Class. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. public class Number_Objects 
  2. {
  3.     static int count=0;
  4.     Number_Objects()
  5.     {
  6.         count++;
  7.     }
  8.     public static void main(String[] args) 
  9.     {
  10.         Number_Objects obj1 = new Number_Objects();
  11.         Number_Objects obj2 = new Number_Objects();
  12.         Number_Objects obj3 = new Number_Objects();
  13.         Number_Objects obj4 = new Number_Objects();
  14.         System.out.println("Number of objects created:"+count);
  15.     }
  16. }

Output:

$ javac Number_Objects.java
$ java Number_Objects
 
Number of objects created:4

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.