Count Objects using Static Variable Java

This program to count the number of objects created for a class using static member function. This is a part of Mumbai University MCA Colleges Java Program


class count
{
 static int count=0;
 public static void main(String arg[])
 {
  count c1=new count(); 
 c1.count();
  count c2=new count();
 c2.count();
  count c3=new count(); 
 c3.count();
  System.out.println("Number of Objects="+count);
 }
 static void count()
 {
 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.


Hope this Program is useful to you in some sense or other. Keep on following this blog for more Mumbai University MCA College Programs. Happy Programming and Studying.

No comments:

Post a comment