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 should describe an entire class of objects instead of a specific object itself. These are called class variables. If you want to keep track of how many Virus objects are being used in a program, you could use a class variable to store this information. 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 associated with a specific object.

Both types of variables are created and used in the same way, but static is part of 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:

tuberculosis.virusCount++;

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

Virus.virusCount++;


Caution

Although class variables are useful, you must take care not to overuse them. These variables exist for as long as the class is running. If a large array of objects is stored in class variables, it will take up a sizeable chunk of memory and never release it.


Both statements accomplish the same thing, but an advantage to using the name of the class when working with class variables is that it shows immediately that virusCount is a class variable instead of an object variable. If you always use object names when working with class variables, you aren’t able to tell whether they are class or object variables without looking carefully at the source code.

Class variables also are called static variables.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.157