Java Reference
In-Depth Information
public void
makeCopy(Clock otherClock)
{
hr = otherClock.hr;
min = otherClock.min;
sec = otherClock.sec;
}
Consider the following statement:
myClock.makeCopy(yourClock);
In this statement, the method
makeCopy
is invoked by
myClock
. The three instance
variables
hr
,
min
,and
sec
inthebodyofthemethod
makeCopy
are the instance
variables of the object
myClock
.Thevariable
yourClock
is passed as a parameter to
makeCopy
. Therefore,
yourClock
and
otherClock
refer to the same object,
which is the object
yourClock
. Thus, after the preceding statement executes, the
instance variables of the object
yourClock
are copied into the corresponding instance
variables of the object
myClock
. (Note that as in the case of the method
equals
,the
parameter
otherClock
can directly access the private data members of the object it
points to.)
The method
getCopy
creates a copy of an object's
hr
,
min
, and
sec
and returns the
address of the copy of the object. That is, the method
getCopy
creates a new
Clock
object, initializes the instance variables of the object, and returns the address of the object
created. The definition of the method
getCopy
is:
public
Clock getCopy()
{
Clock temp =
new
Clock();
//Line 1
temp.hr = hr;
//Line 2
temp.min = min;
//Line 3
temp.sec = sec;
//Line 4
return
temp;
//Line 5
}
The following illustrates how the method
getCopy
works. Suppose that
yourClock
is as
shown in Figure 8-11.
hr 4
min 18
sec 39
yourClock
FIGURE 8-11
Object
yourClock
Search WWH ::
Custom Search