Java Objects |
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.Every time you instantiate AnIntegerNamedX, you create an instance of AnIntegerNamedX and each instance of AnIntegerNamedX gets its own copy ofclass AnIntegerNamedX { int x; }x
. To access a particularx
, 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 accessx
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.The output produced by this code snippet is. . . 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); . . .illustrating that each instance of the class AnIntegerNamedX has its own copy of the instance variablemyX.x = 1 anotherX.x = 2x
.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 itsx
variable is now a class variableNow the exact same code snippet from before that creates two instances of AnIntegerNamedX, sets theirclass AnIntegerNamedX { static int x; }x
values, and then prints thex
values produces this, different, output.That's because now thatmyX.x = 2 anotherX.x = 2x
is a class variable there is only one copy of the variable and it is shared by all instances of AnIntegerNamedX includingmyX
andanotherX
.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).
Table of Contents |