Java Reference
In-Depth Information
12.
The class
NickName
given in Segment C.3 of Appendix C has a data field that is an instance of the class
Name
and two methods,
setNickName
and
getNickName
. Implement a method
clone
for
NickName
, assuming that
Name
implements the interface
Cloneable
.
13.
Consider a class that implements
ListInterface
but does not make clones of objects added to the list. Suggest
two ways that we can make a list of clones.
14.
Consider a class that implements
ListInterface
and makes clones of objects added to the list. Suggest two ways
that we can make a list of the original objects.
15.
Consider the following class definition:
public class
FamilyMember
implements
Cloneable
{
private
Name myName;
private
FamilyMember mySpouse;
public
FamilyMember(Name aName)
{
myName = aName;
}
// end constructor
public
Name getName()
{
return
myName;
}
// end getName
public
FamilyMember getSpouse()
{
return
mySpouse;
}
// end getSpouse
public
void
setSpouse(FamilyMember spouse)
{
mySpouse = spouse;
}
// end setSpouse
public
Object clone()
{
FamilyMember theCopy =
null
;
try
{
theCopy = (FamilyMember)
super
.clone();
}
catch
(CloneNotSupportedException e)
{
System.err.println("FamilyMember cannot clone:" + e.toString());
}
return
theCopy;
}
// end clone
}
// end FamilyMember
Draw a diagram showing the state of the objects after the following code executes.
FamilyMember jack =
new
FamilyMember(
new
Name("Jack", "Buck"));
FamilyMember jane =
new
FamilyMember(
new
Name("Jane", "Doe"));
jack.setSpouse(jane);
jane.setSpouse(jack);
FamilyMember copy = (FamilyMember)jane.clone();
16.
Replace the method
copy
, as discussed in Segment 24.6 of Chapter 24, with a method
clone
. That is, make
BinaryNode
implement the interface
Cloneable
. Cloning a node should also clone the node's data object.