Java Reference
In-Depth Information
Reference variables can be passed as parameters to methods and returned as method
values. Recall from Chapter 7 that when a reference variable is passed as a parameter to a
method, both the formal and actual parameters point to the same object.
of the
class
Clock
We now give the definitions of the methods of the
class
Clock
, then we will write the
complete definition of this class. First, note the following:
1. The
class
Clock
has 11 methods:
setTime
,
getHours
,
getMinutes
,
getSeconds
,
printTime
,
incrementHours
,
incrementMinutes
,
incrementSeconds
,
equals
,
makeCopy
, and
getCopy
. It has two
constructors and three instance variables:
hr
,
min
, and
sec
.
2. The three instance variables—
hr
,
min
, and
sec
—are
private
to the
class
and cannot be accessed directly outside the
class
.
3. The 11 methods—
setTime
,
getHours
,
getMinutes
,
getSeconds
,
printTime
,
incrementHours
,
incrementMinutes
,
incrementSeconds
,
equals
,
makeCopy
,and
getCopy
—can directly access the instance vari-
ables (
hr
,
min
,and
sec
). In other words, we do not pass instance
variables or data members as parameters to these methods. Similarly,
constructors directly access the instance variables.
Let's first write the definition of the method
setTime
. The method
setTime
has three
parameters of type
int
. This method sets the instance variables to the values specified by
the user, which are passed as parameters to this function. The definition of the method
setTime
follows:
8
public void
setTime(
int
hours,
int
minutes,
int
seconds)
{
if
(0 <= hours && hours < 24)
hr = hours;
else
hr = 0;
if
(0 <= minutes && minutes < 60)
min = minutes;
else
min = 0;
if
(0 <= seconds && seconds < 60)
sec = seconds;
else
sec = 0;
}
Search WWH ::
Custom Search