Java Reference
In-Depth Information
As you can see, the interface is empty. It declares no methods and serves only as a way for a class to indi-
cate that it implements
clone
. If you forget to write
implements
Cloneable
in your class definition,
instances of your class that invoke
clone
will cause the exception
CloneNotSupportedException
.
This result can be confusing at first, particularly if you did implement
clone
.
Programming Tip:
If your program produces the exception
CloneNotSupported
-
Exception
even though you implemented a method
clone
in your class, you probably forgot
to write
implements
Cloneable
in your class definition.
Note:
The
Cloneable
interface
The empty
Cloneable
interface is not a typical interface. A class implements it to indicate
that it will provide a public
clone
method. Since the designers of Java wanted to provide a
default implementation of the method
clone
, they included it in the class
Object
and not in
the interface
Cloneable
. But because the designers did not want every class to automatically
have a public
clone
method, they made
clone
a protected method.
Note:
Cloning
Cloning is not an operation that every class should be able to do. If you want your class to
have this ability, you must
•
Declare that your class implements the
Cloneable
interface
•
Override the protected method
clone
that your class inherits from the class
Object
with a public version
30.15
Example: Cloning a
Name
object.
Let's add a method
clone
to the class
Name
of Segment B.16 in
Appendix B and Segment 30.10. Before we begin, we should add
implements
Cloneable
to the
first line of the class definition, as follows:
public class
Name
implements
Cloneable
The public method
clone
within
Name
must invoke the method
clone
of its superclass by exe-
cuting
super.clone()
. Because
Name
's superclass is
Object
,
super.clone()
invokes
Object
's
protected method
clone
.
Object
's version of
clone
can throw an exception, so we must enclose
each call to it in a
try
block and write a
catch
block to handle the exception. The method's final
action should return the cloned object.
Thus,
Name
's method
clone
could appear as follows:
public
Object clone()
{
Name theCopy =
null
;
try
{
theCopy = (Name)
super
.clone();
// Object can throw an exception
}
catch
(CloneNotSupportedException e)
{
System.err.println("Name cannot clone: " + e.toString());
}
return
theCopy;
}
// end clone