Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

140 HOUR 11:Describing What Your Object Is Like


has its own version of the newSeconds, maxFileSize, and authorvariables.
If you modified one of these variables in an object, it would not affect the
same variable in another Virusobject.
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 Virusobjects 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 variablesbecause they are associated
with a specific object.
Both types of variables are created and used in the same way, but staticis
part of the statement that creates class variables. The following statement
createsa class variable for the Virusexample:
static int virusCount = 0;

Changing the value of a class variable is no different than changing an
object’s variables. If you have a Virusobject called tuberculosis, you
could change the class variable virusCountwith 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++;

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 imme-
diately that virusCountis 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 staticvariables.

Creating Behavior with Methods
Attributes are the way to keep track of information about a class of objects,
but for a class to do the things it was created to do, you must create behav-
ior. Behavior describes the parts of a class that accomplish specific tasks.
Each of these sections is called a method.

CAUTION
Although class variablesare
useful,you must take care not
to overuse them. These vari-
ables 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 size-
able chunk of memory and
never release it.

Free download pdf