Java Reference
In-Depth Information
In other words, the values of the three instance variables of the object yourClock are copied
into the corresponding instance variables of the object myClock , as shown in Figure 8-6.
hr 7
min 27
hr 7
min 27
myClock
yourClock
sec 36
sec 36
FIGURE 8-6 Objects myClock and yourClock after the statement
myClock.makeCopy(yourClock); executes
This is called the deep copying of data. In deep copying, each reference variable refers
to its own object, as in Figure 8-6, not the same object, as in Figure 8-5.
Another way to avoid the shallow copying of data is to have the object being copied
create a copy of itself, and then return a reference to the copy. This is accomplished by
the method getCopy . Consider the following statement:
myClock = yourClock.getCopy();
In this statement, the expression yourClock.getCopy() makes a copy of the object
yourClock and returns the address, that is, the reference, of the copy. The assignment
statement stores this address into myClock .
The methods makeCopy and getCopy arebothusedtoavoidtheshallowcopying
of data. The main difference between these two methods is: To use the method
makeCopy , both objects—the object whose data is being copied and the object
that is copying the data—must be instantiated before invoking this method. To use
the method getCopy , the object whose data is being copied must be instantiated
before invoking this method, while the object of the reference variable receiving a
copy of the data need not be instantiated. Note that makeCopy and getCopy are
user-defined methods.
It is important to understand the difference between the shallow and deep copying of data
and when to use which. Shallow copying can produce unintended results, especially
by beginning Java programmers.
Class Scope
A reference variable follows the same scope rules as other variables. A member of a class is
local to the class. You access a public class member outside the class through the
reference variable name or the class name (for static members) and the member
access operator ( . ).
 
 
 
Search WWH ::




Custom Search