Java Reference
In-Depth Information
There is a reason why the Object.clone method does not systematically
clone all sub-objects. In some situations, it is unnecessary. For example, if an
object contains a reference to a string, there is no harm in copying the string
reference, because Java string objects can never change their contents. The
Object.clone method does the right thing if an object contains only
numbers, Boolean values, and strings. But it must be used with caution when an
object contains references to other objects.
For that reason, there are two safeguards built into the Object.clone method
to ensure that it is not used accidentally. First, the method is declared
protected (see Advanced Topic 10.3 ). This prevents you from accidentally
calling x.clone() if the class to which x belongs hasn't redefined clone to
be public.
As a second precaution, Object.clone checks that the object being cloned
implements the Cloneable interface. If not, it throws an exception. The
Object.clone method looks like this:
public class Object
{
protected Object clone()
throws CloneNotSupportedException
{
if (this instanceof Cloneable)
{
// Copy the instance fields
. . .
}
else
throw new CloneNotSupportedException();
}
}
Unfortunately, all that safeguarding means that the legitimate callers of
Object.clone() pay a priceȌthey must catch that exception even if their
class implements Cloneable .
public class BankAccount implements Cloneable
{
. . .
public Object clone()
474
475
Search WWH ::




Custom Search