Java Reference
In-Depth Information
copy' operation." To remember the precise function of
Object.clone()
, it helps to think
of this method as if it were named
Object.newObjectSameFields()
.
SOLUTION 18.4
One solution is:
public Object clone()
{
OzTextArea ta = new OzTextArea();
ta.setFont(textArea().getFont());
ta.setCursor(getCursor());
return ta;
}
To copy an
OzTextArea
object, this code creates a new object and explicitly sets the
instance variables that the new object must reproduce from its prototype.
SOLUTION 18.5
The code given in the challenge produces three objects, as Figure B.24 shows. The current
version of the
clone()
method for
MachineSimulator
calls
super.clone()
, which
class
Object
implements. This method creates a new object with the same fields. Primitive
types, such as the
int
instance fields in a
MachineSimulator
, are copied. In addition,
object references, such as the
Location
field in
MachineSimulator
, are copied. Note
that the
reference
is copied, not the object. This means that
Object.clone()
produces
the situation that Figure B.24 shows.
Figure B.24. An insufficient design for cloning can create an incomplete copy that shares
some objects with its prototype.
The code in the challenge changes the bay and the coordinates of the second machine's
location. However, because there is only one
Location
object, these modifications change
the location of both simulations. Thus, the
println()
statement displays
2
as the value of
m1.location.bay
.
SOLUTION 18.6
A reasonable solution is as follows: