Java Reference
In-Depth Information
Suppose that the objects
myClock
and
yourClock
are as shown in Figure 8-4.
hr
10
hr
7
myClock
yourClock
min 28
sec 45
min 27
sec 36
FIGURE 8-4
myClock
and
yourClock
The statement:
myClock = yourClock;
copies the value of the reference variable
yourClock
into the reference variable
myClock
. After this statement executes, both
yourClock
and
myClock
refer to the same
object. Figure 8-5 illustrates this situation.
8
hr 10
min 28
sec 45
hr 7
min 27
sec 36
myClock
yourClock
FIGURE 8-5
myClock
and
yourClock
after the statement
myClock
ΒΌ
yourClock;
executes
This is called the shallow copying of data. In shallow copying, two or more reference
variables of the same type point to the same object; that is, two or more reference
variables become aliases. Note that the object originally referred to by
myClock
becomes
inaccessible.
To copy the instance variables of the object
yourClock
into the corresponding instance
variables of the object
myClock
, you need to use the method
makeCopy
. This is
accomplished by the following statement:
myClock.makeCopy(yourClock);
After this statement executes:
1. The value of
yourClock.hr
is copied into
myClock.hr
.
2. The value of
yourClock.min
is copied into
myClock.min
.
3. The value of
yourClock.sec
is copied into
myClock.sec
.
Search WWH ::
Custom Search