Static

index
INTERMEDIATE

Special note to C programmers: static means something entirely different in Java than it does in C.

A class is a description of objects. Almost all variables declared within a class belong to the objects of that class, not to the class itself; these are called instance variables. In the picture below, name is an instance variable, and each of the three Dog objects has its own copy ("instance") of this variable. The class itself does not "have" a name variable; it just describes that variable, so that when you create Dog objects, Java knows what variables to put in them.

Similarly, almost all methods declared in a class belong to the objects of the class; these can be called instance methods, though this term is rarely used. In the above picture, toString is an instance method that returns the name of the object to which it belongs.

If you want the class itself to have a variable, declare it as static. A static variable (or class variable) is one that belongs to the class itself, rather than to the objects of the class. In the above example, count is a variable that might be used to keep track of how many Dog objects have been created.

Because a static variable belongs to the class itself, there is only one of it, not one for each object. If you change the value of this variable, it is changed in the class. Individual Dog objects can use static variables just like any other (because every object knows what class it belongs to), but individual dogs don't have a "count." What is Fido's count? That doesn't make sense.

Likewise, a static method (no example shown) belongs to the class itself, not to individual objects of that class. This means:

When should you use static?

The general rule is: Avoid static. However,

A static method cannot use a non-static variable or method (those belong to the actual objects); if you try to do this, you will get the following error message:

non-static variable [or method] Name cannot be referenced from a static context

The correct way to fix this error is almost always to make the calling method non-static, rather than to make the called method static. You can avoid most such problems by starting your program as follows: Have your main method create an object of whatever class it is in, and call an instance method of that object to do the actual work. Like this:

public class MyClass {
 
    public static void main(String[] args) {
        MyClass slave = new MyClass();
        slave.doAllTheWork();
    }
 
    void doAllTheWork() {
        // Start the real work here...
    }
}