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