SE450: Java classes: clone() [18/22] ![]() ![]() ![]() |
We have looked at the equals, toString, and hashCode methods
that are all inherited from Object
. We now need to
look at the clone
method.
It is analogous to the Copy constructor in C++
The intent is that
x.clone() != x x.clone().getClass() == x.getClass() x.clone().equals(x)
The last intent is not a requirement, but is generally true.
By convention, you obtain the returned object by calling
super.clone()
. If all superclasses do this,
then x.clone().getClass() == x.getClass()
will
be true.
Object
doesn't implement Cloneable
itself
The Cloneable
interface is meant to be a
mixin interface, however it doesn't do a very good job of this.
The Cloneable
interface doesn't contain the clone
method, so classes can't be guaranteed to call this method (it may not
have the right visibility). But since it is in pretty wide use,
we should understand it. We will look at a design pattern, the
Prototype in a few weeks that is a better way to do this.
However, you need to be concerned about the deep vs. shallow copy problem. If a there are mutable objects that are members of the object being cloned, they may need to be copied during the clone operation, and references to the objects changed to point to the new objects.
To clone you need:
Cloneable
interface
(note the misspelling)
Object.clone
method (or your superclass's
clone method)
CloneNotSupportedException
, to signal the
clone method shouldn't have been called.
You can:
Object.clone
method, but it is
protected, so it is not of much use for other classes to use.