Java Reference
In-Depth Information
dieValue = getRandomDieValue() ;
}
public int
getValue ()
{
if
(dieValue
>
=1 && dieValue
<
=6)
{
return
dieValue ;
}
else
{
return
0;
}
}
{
private static int
getRandomDieValue ()
return
(
int
)
(Math . random ( )
∗
6+1);
}
}
The
setValue
method is substituted with the more appropriate
rollDie
method. In
other words, we do not allow someone from the outside world to set the value of a die. They
canonlycallthe
rollDie
method to change the value of a die to a random number. The
getValue
method is changed to return the value of the variable
dieValue
only when it is in
the correct range. Note that in the above example it is obvious that
dieValue
will always
be between 1 and 6. However, as more methods are added to the
Die
class, this does not
need to be the case.
Every class can contain two types of methods:
static
and
instance
. A method is
defined as static by adding the
static
keyword to its definition. The absence of the
static
keyword in the definition of a method implies that the method is instance.
Static methods are called on the class and have access only to the static variables of
the class. Instance methods are called on an object of the class and have, in addition,
access to the instance variables of the object on which they are called.
For example, if
d
is a
Die
object, then
d.rollDie()
will change the state of the die
object. When we refer to the variable
dieValue
in the
rollDie
method, we are actually
referring to
d.dieValue
(i.e., the variable
dieValue
for the
d
object). We will sometimes
refer to the object on which the method is called (e.g.,
d
in the above example) as the
hidden
parameter
of the method. An instance method uses this object as a parameter without the
object being directly passed as a parameter.
Static methods do not possess a hidden parameter. They are called on the whole
class and not on a particular object. From within the class, a static method can be in-
voked just by referring to its name. This is the case inside the
rollDie
method, where
the static
getRandomDieValue
method is directly invoked. From outside the class, the
getRandomDieValue
method can be invoked as follows:
Die.getRandomDieValue()
.How-
ever, this will only work as long as the declaration of the
getRandomDieValue
method is
changed to
public
. Remember that
public
data and methods can be accessed from ev-
erywhere. Conversely,
private
data and methods can only be accessed within the class in
which they are defined.
Note that a static method
can
be invoked on an object. However, this call is rewritten
to call the method on the class that the object belongs to. For example, if
Die
is a public
method and
d
is an object of type
Die
,then
System. out . println (d. getRandomDieValue () ) ;
will be rewritten by Java as follows.