Friday, February 21, 2014

How static data Members work in Java

Here you can find the detailed description of how static data members work in java:

Inside a class' body if a field (also called data member) is declared static then there will exist exactly one copy of that field, no matter how many objects of the class are finally created. A static field, also called a class variable comes into existence when the class is initialized. Data members declared as static are essentially global variables. When objects of its class are created they share the same copy of static field. Following example program demonstrates static data members working nature:


 class StaticField
{
    static int objectCount = 0;

    public StaticField()
    {
        objectCount++;
    }

    public String toString()
    {
        return new String ("There are " + objectCount + " objects of class " + this.getClass().getName());
    }

    public static String numOfObjects()
    {
        return new String ("There are " + objectCount + " objects of class " + StaticField.class.getName());
    }
}

public class StaticFieldDemo
{
    public static void main(String[] args)
    {
        System.out.println(StaticField.numOfObjects());
       
        StaticField s1 = new StaticField();
        StaticField s2 = new StaticField();
        StaticField s3 = new StaticField();
 
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
    }
}

OUTPUT
======
There are 0 objects of class StaticField
There are 3 objects of class StaticField
There are 3 objects of class StaticField
There are 3 objects of class StaticField

Read above program carefully, you will see a field objectCount of type int that is declared static. As it has been explained, a static field is initialized when a class is initialized. Field objectCount is initialized with 0 when class is initialized and then gets incremented by 1 each time when an object of class StaticField is created as the increment code is present inside the body of zero argument constructor of the class.
Now come to the main() method of class StaticFieldDemo and see the first statement that prints the value of objectCount and it is zero at this point. Then three objects of class StaticField are created and every time objectCount is incremented. As there is only copy of objectCount is maintained globally at the class level. So when objectCount is printed by objects s1, s2, and s3, they all print the same value.

No comments:

Post a Comment