Java Reference
In-Depth Information
{
try
{
return super.clone();
}
catch (CloneNotSupportedException e)
{
//
CanȐt happen because we implement
Cloneabl e
but
we still must catch it.
return null;
}
}
}
If an object contains a reference to another mutable object, then you must call
clone
for that reference. For example, suppose the
Customer
class has an
instance field of class
BankAccount
. You can implement
Customer.clone
as follows:
public class Customer implements Cloneable
{
. . .
public Object clone()
{
try
{
Customer cloned = (Customer)
super.clone();
cloned.account = (BankAccount)
account.clone();
return cloned;
}
catch(CloneNotSupportedException e)
{
//
CanȐt happen because we implement
Cloneabl e
return null;
}
}
private String name;
private BankAccount account;
}