Count Objects using Static Variable Java

Ram Pothuraju
This program to count the number of objects created for a class using static member function. 

class count 

 static int count=0; 
 public static void main(String arg[]) 
  count c1=new count(); 

  count c2=new count();
  count c3=new count(); 
  System.out.println("Number of Objects="+count);
 static void count()

In the above program we have taken a static variable name count. Static variable are called as class variables. There is only once instance of a static variable for whole class and all the objects of the class. In this program we increment the static variable count when we call the count() function with the object. All objects c1, c2 and c3 access the same variable and hence we can find the count of the objects created.

Post a Comment


Post a Comment (0)