Java Reference
In-Depth Information
< Constructors and the methods
setStudent
,
setYear
,
getYear
,
setDegree
,
getDegree
,
and
toString
>
. . .
}
// end CollegeStudent
The data fields of a
CollegeStudent
object are a primitive value and an immutable object, and
so they do not need to be cloned. Thus, the definition of
clone
that we add to
CollegeStudent
is as
follows:
public
Object clone()
{
CollegeStudent theCopy = (CollegeStudent)
super
.clone();
return
theCopy;
}
// end clone
The method must call
Student
's
clone
method, and it does so with the invocation
super.clone()
.
Note that since
Student
's
clone
method does not throw an exception, no
try
block is necessary
when we call it. Had
CollegeStudent
defined fields that needed to be cloned, we would clone them
right before the
return
statement.
30.20
The class
AList
that you saw in Chapter 13 uses an array to implement the ADT list. Suppose that we
want to add a
clone
method to this class.
While making a copy of the list,
clone
needs to copy the array and all the objects in it. Thus,
the objects in the list must have a
clone
method as well. Recall that
AList
defines a generic type
T
for the objects it contains. Beginning
AList
as
public class
AList<T
extends
Cloneable> . . .
// incorrect
will not work correctly, since the interface
Cloneable
is empty.
Instead, we define a new interface that declares a public method
clone
to override
Object
's
protected method:
public interface
Copyable
extends
Cloneable
{
public
Object clone();
}
// end Copyable
We then can begin
AList
with any one of the following statements:
•
public class
AList<T
extends
Copyable>
implements
ListInterface<T>, Cloneable
•
public class
AList<T
extends
Copyable>
implements
ListInterface<T>, Copyable
•
public class
AList<T
extends
Copyable>
implements
CloneableListInterface<T>
where
CloneableListInterface
is defined as follows:
public interface
CloneableListInterface<T>
extends
ListInterface<T>, Copyable
// or Cloneable
{
}
// end CloneableListInterface
The notation
AList<T
extends
Copyable>
requires the objects in the list to belong to a class that implements our interface
Copyable
.
Note that
CloneableListInterface
extends two interfaces,
ListInterface
and either
Copyable
or
Cloneable
. As noted in Segment D.25 of Appendix D, an interface can extend
more than one interface, even though a class can extend only one other class.