Static Members: Static Methods and Static Variables

Why do we need Static members?

There are situations in which the method’s behaviour does not depend on the state of an object. So, there will be no use of having an object when the method itself will not be instance specific.

Let us consider another situation where in we want to keep a count of all the instances instantiated from a particular class. Suppose we declare an instance variable to do the job, it won’t work. Its because the instance variables are initialised back to their default value each time a instance is created. So we need some varaible which will be independent of the instances created.

The answer to both the situations is to use the “static” modifiers, in other words static members.

What exactly are Static Variable and Methods?

Variables and methods marked static belong to the class rather than to any particular instance of the class. These can be used without having any instances of that class at all. Only the class is sufficient to invoke a static method or access a static variable. A static variable is shared by all the instances of that class i.e only one copy of the static variable is maintained.

class Animal
{

static int animalCount=0;
public Animal()
{

animalCount+=1;

}
public static void main(String[] args)
{

new Animal();
new Animal();
new Animal();
System.out.println(“The Number of Animals is: “+ animalCount);

}

}

The output is – “The Number of Animals is 3“.

A static method cannot access non-static/instance variables, because a static method is never associated with any instance. The same applies with the non-static methods as well, a static method can’t directly invoke a non-static method. But static method can access non-static methods by means of declaring instances and using them.

Note: One of the mistakes most often made by new Java programmers is accessing instance variables from main() method.

How to go about Accessing them?

In case of instance methods and instance variables, instances of that class are used to access them.

<objectReference>.<instanceVariable>
<objectReference>.<instanceMethod>

But static members are not associated with any instances. So there is no point in using the object. So, the way static methods (or static variables) are accessed is by using the dot operator on the class name, as opposed to using it on a reference to an instance.

class Animal
{

static int animalCount=0;
public Animal()
{

animalCount+=1;

}
public static int getCount()
{

return animalCount;

}

}

class TestAnimal
{

public static void main(String[] args)
{

new Animal();
new Animal();
new Animal();
System.out.println(“The Number of Animals is: “+ Animal.getCount());
/*
Notice the way in which the Static method is called using the class name followed by static method.

*/

}

}

Remember that static methods can’t be overridden. They can be redefined in a subclass, but redifining and overriding aren’t the same thing. Its called as Hiding. One can read the article on Overriding Vs Hiding here.

Advertisements

17 thoughts on “Static Members: Static Methods and Static Variables

  1. sree

    What is the difference between Abstract class and interfaces very clearly?

    when u will use abstract class and interfaces with example?

    Like

    Reply
  2. Mohamed Sanaulla

    Abstract classes are extended where as Interfaces are implemented which means we can implement multiple interfaces but can extend from one abstract class. Interfaces are used for supporting Multiple Inheritance kind feature (Not Multiple Inheritance exactly).

    Abstract classes can also contain non abstract methods. But interfaces have only abstract methods (Abstract methods are methods without body).

    More details about Interfaces can be found here

    Read about differences here.

    Like

    Reply
  3. Bikram Panjikar

    In some cases, certain members should only belong to the class, and not be part of any object created from the class. An example of such a situation is when a class wants to keep track of how many objects of the class have been created. Defining a counter as an instance variable in the class definition for tracking the number of objects created, does not solve the problem. Each object created will have its own counter field. Which counter should then be updated? The solution is to declare the counter field as being static. Such a field is called a static variable. It belongs to the class, and not to any object of the class. A static variable is initialized when the class is loaded at runtime. Similarly, a class can have static methods that belong only to the class, and not to any objects of the class. Static variables and static methods are collectively known as static members, and are distinguished from instance members in a class definition by the keyword static in their declaration.

    public class CharStack
    {
    private char[] stackArray;
    private int topOfStack;
    private static int counter;
    public CharStack(int capacity)
    {
    stackArray = new char[capacity];
    topOfStack = -1;
    counter++;
    }
    public void push(char element) { stackArray[++topOfStack] = element; }
    public char pop() { return stackArray[topOfStack–]; }
    public char peek() { return stackArray[topOfStack]; }
    public boolean isEmpty() { return topOfStack < 0; }
    public boolean isFull() { return topOfStack == stackArray.length – 1; }
    public static int getInstanceCount() { return counter; }
    }

    Like

    Reply
  4. cesar

    Hi sanaulla, about your example class TestAnimal.java, I have one cuestion:

    Can I acces the static int countAnmial variable from another program????
    for example:
    1. In on consolo puto to run TestAnimal.java in while loop, the output should be something like: 3, 6, 9 an so on

    2. Mean while, if i wrote another java program (Jp2.java) witch void main containing something like:
    System.out.println(“The Number of Animals is: “+ Animal.getAnimalCount());

    3. Why I can’t acces and show from Jp2.java t the value of Animal.getAnimalCount() that is increasing by the other program ????

    Thanks for your answer.

    Like

    Reply
    1. Mohamed Sanaulla Post author

      Every Java program you launch will run with in its own JVM instance and they are 2 different process which means each has its own memory- heap and stack area. To communicate between the programs you can make use of any of the IPC mechanisms.

      Like

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s