Java Reference
In-Depth Information
Instance Data
Note that in the
Die
class, the constant
MAX
and the variable
faceValue
are declared
inside the class but not inside any method. The location at which a variable is
declared defines its
scope,
which is the area within a program in which that vari-
able can be referenced. By being declared at the class level (not within a method),
these variables and constants can be referenced in any method of the class.
Attributes such as the variable
faceValue
are called
instance
data
because new memory space is reserved for that variable every
time an instance of the class that is created. Each
Die
object has its
own
faceValue
variable with its own data space. That's how each
Die
object can have its own state. We see that in the output of the
RollingDice
program: one die has a face value of 5 and the other has a face value
of 2. That's possible only because the memory space for the
faceValue
variable
is created for each
Die
object.
We can depict this situation as follows:
KEY CONCEPT
The scope of a variable, which deter-
mines where it can be referenced,
depends on where it is declared.
die1
faceValue
5
die2
faceValue
2
The
die1
and
die2
reference variables point to (that is, contain the address
of) their respective
Die
objects. Each object contains a
faceValue
variable
with its own memory space. Thus each object can store different values for its
instance data.
Java automatically initializes any variables declared at the class level. For
example, all variables of numeric types such as
int
and
double
are initialized to
zero. However, despite the fact that the language performs this automatic initial-
ization, it is good practice to initialize variables explicitly (usually in a construc-
tor) so that anyone reading the code will clearly understand the intent.
UML Class Diagrams
Throughout this topic we use
UML diagrams
to visualize relationships among
classes and objects. UML stands for the
Unified Modeling Language,
which
has become the most popular notation for representing the design of an object-
oriented program.
Several types of UML diagrams exist, each designed to show specific aspects
of object-oriented programs. We focus primarily on UML
class diagrams
in this
book to show the contents of classes and the relationships among them.
Search WWH ::
Custom Search