Java Reference
In-Depth Information
For example, the VolcanoRobot class defines a speed instance variable. This must be an
instance variable because each robot travels at different speeds. The value of a robot's
speed instance variable could be changed to make the robot move more quickly or
slowly.
Instance variables can be given a value when an object is created and then stay constant
throughout the life of the object. They also can be given different values as the object is
used in a running program.
For other variables, it makes more sense to have one value shared by all objects of that
class. These attributes are called class variables.
A class variable defines an attribute of an entire class. The variable applies to the class
itself and to all its instances, so only one value is stored no matter how many objects of
that class have been created.
An example of a class variable for the VolcanoRobot class would be a variable that holds
the current time. If an instance variable were created to hold the time, each object could
have a different value for this variable, which could cause problems if the robots are sup-
posed to perform tasks in conjunction with each other.
Using a class variable prevents this problem because all objects of that class share the
same value automatically. Each VolcanoRobot object would have access to that variable.
Behavior of a Class of Objects
Behavior refers to the things that a class of objects can do to themselves and other
objects. Behavior can be used to change the attributes of an object, receive information
from other objects, and send messages to other objects asking them to perform tasks.
A volcano robot could have the following behavior:
Check current temperature
n
Begin a survey
n
Report its current location
n
Behavior for a class of objects is implemented using methods.
Methods are groups of related statements in a class that perform a specific task. They are
used to accomplish specific tasks on their own objects and on other objects and are com-
parable to functions and subroutines in other programming languages.
Objects communicate with each other using methods. A class or an object can call meth-
ods in another class or object for many reasons, including the following:
Search WWH ::




Custom Search