Programming and Problem Solving with Java

(やまだぃちぅ) #1
7.7 Copy Constructors | 353

Here’s an example of how it would be called, where oldAccountis an existing
object of type SavingsAccountand addressis a string that holds a new address
value for the account:


account = new SavingsAccount(oldAccount, address);


The body of the constructor would copy every field from oldAccountto its own
equivalent fields, substituting the value in its addressparameter for the one in the
addressfield of oldAccount. Note that if any of the fields in the object are themselves
objects, we must use their observers to copy the actual values from the fields of
the nested objects. Otherwise, the new object simply refers to the same places in
memory as oldAccount.
This copy constructor is said to perform a deep copyof the object. A deep
copy copies what a reference refers to, rather than the reference itself. A shal-
low copyignores the presence of nested objects, treating them like fields of
simple types. Figure 7.4 illustrates shallow copying, and Figure 7.5 shows deep
copying. In both figures, the colored arrows indicate that a field is a reference
type with an address that specifies another place in memory. The black arrows
indicate copying of values.


New SavingsAccount
Object
account = 4295110
name =
address =
phone =
balance = 8337.26
activation =
status = 1

Existing SavingsAccount
Object

account = 4295110
name =
address =
phone =
balance = 8337.26
activation =
status = 1

Existing Nested Objects

"Jane A. Smith"

"4731 East Oak St., Fossil, OR, 97364"

"541-555-9111"

month =
day = 17
year = 1993

"August"

Figure 7.4 Shallow Copying


Deep copy An operation that
copies one class instance to an-
other, using observer methods
as necessary to eliminate nested
references and copy only the
simple types to which they refer;
the result is that the two
instances do not contain any du-
plicate references
Shallow copy An operation
that copies a source class
instance to a destination class
instance, simply copying all ref-
erences so that the destination
instance contains duplicate ref-
erences to values that are also
referred to by the source
Free download pdf