Creating Class Variables

When you create an object, it has its own version of all variables that are part of the object's class. Each object created from the Virus class of objects has its own version of the newSeconds, maxFileSize, and author variables. If you modified one of these variables in an object, it would not affect the same variable in another Virus object. There are times when an attribute has more to do with an entire class of objects than a specific object itself. For example, if you wanted to keep track of how many Virus objects were being used in a program, it would not make sense to store this value repeatedly in each Virus object. Instead, you can use a class variable to store this kind of information. You can use this kind of variable with any object of a class, but only one copy of the variable exists for the whole class. The variables you have been creating for objects thus far can be called object variables, because they are tied to a specific object. Class variables refer to a class of the objects as a whole. Both types of variables are created and used in the same way, except that static is used in the statement that creates class variables. The following statement creates a class variable for the Virus example:

static int virusCount = 0;

Changing the value of a class variable is no different than changing an object's variables. If you have a Virus object called tuberculosis, you could change the class variable virusCount with the following statement:


Because class variables apply to an entire class instead of a specific object, you can use the name of the class instead:


Both statements accomplish the same thing, but there's an advantage to using the name of the class when working with class variables. It shows immediately that virusCount is a class variable instead of an object's variable, because you can't refer to object variables using the name of a class. If you always use object names when working with class variables, you won't be able to tell whether they are class or object variables without looking carefully at the source code of the class.