Java Reference
In-Depth Information
Consider the following statement:
myClock = yourClock.getCopy();
//Line A
In this statement, because the method getCopy is invoked by yourClock , the three
variables hr , min , and sec in the body of the method getCopy are the instance variables
of the object yourClock . The body of the method getCopy executes as follows. The
statement in Line 1 creates the Clock object temp . The statements in Lines 2 through 4
copy the instance variables of the object yourClock into the corresponding instance
variables of temp . In other words, the object referenced by temp is a copy of the object
yourClock (see Figure 8-12).
hr 4
min 18
sec 39
hr 4
min 18
sec 39
temp
yourClock
FIGURE 8-12 Objects temp and yourClock
8
The statement in Line 5 returns the value of temp , which is the address of the object
holding a copy of the data. The value returned by the method getCopy is copied into
myClock . Therefore, after the statement in Line A executes, myClock and yourClock
are as shown in Figure 8-13.
hr 4
min 18
sec 39
hr 4
min 18
sec 39
myClock
yourClock
FIGURE 8-13 Objects myClock and yourClock
Note that as in the case of the methods equals and makeCopy , the reference variable
temp —in the definition of the method getCopy —can directly access the private
data members of the object it points to because getCopy is a method of the class
Clock .
 
Search WWH ::




Custom Search