Previous | Next | Trail Map | Writing Java Programs | Java Objects


Declaring a Class Variable

By default, when you declare a variable within a class that variable is an instance variable. Every time you instantiate a new object from the class, you get a new copy of each instance variable of that class, and that copy is associated with the new object. For example, the class defined below has one instance variable, an integer named x.
class AnIntegerNamedX {
    int x;
}
Every time you instantiate AnIntegerNamedX, you create an instance of AnIntegerNamedX and each instance of AnIntegerNamedX gets its own copy of x. To access a particular x, you must access it through the object with which it is associated (either directly, if you have access, or through the instance's methods). There is no other way to access x except through the instance.

This code snippet creates two different objects of type AnIntegerNamedX, sets their x values to different values, then prints out the values.

. . .
AnIntegerNamedX myX = new AnIntegerNamedX();
AnIntegerNamedX anotherX = new AnIntegerNamedX();
myX.x = 1;
anotherX.x = 2;
System.out.println("myX.x = " + myX.x);
System.out.println("anotherX.x = " + anotherX.x);
. . .
The output produced by this code snippet is
myX.x = 1
anotherX.x = 2
illustrating that each instance of the class AnIntegerNamedX has its own copy of the instance variable x.

However, when declaring a variable, you can specify that variable to be a class variable rather than an instance variable. The system creates a single copy of a class variable the first time it encounters the class in which the variable is defined. All instances of that class share the same class variable.

To specify that a variable is a class variable, use the keyword static. For example, let's change the AnIntegerNamedX class such that its x variable is now a class variable

class AnIntegerNamedX {
    static int x;
}
Now the exact same code snippet from before that creates two instances of AnIntegerNamedX, sets their x values, and then prints the x values produces this, different, output.
myX.x = 2
anotherX.x = 2
That's because now that x is a class variable there is only one copy of the variable and it is shared by all instances of AnIntegerNamedX including myX and anotherX.

You use class variables for items that you need only one copy of and which must be accessible by all objects inheriting from the class in which the variable is declared. For example, class variables are often used to define constants (this is more memory efficient as constants can't change so you really only need one copy).


Previous | Next | Trail Map | Writing Java Programs | Table of Contents