Interview Questions

The Cloneable interface and deep copies

Java Interview Questions for Cloning and Cloneable


(Continued from previous question...)

The Cloneable interface and deep copies

By default, classes in Java do not support cloning; the default implementation of the clone() method throws a CloneNotSupportedException. You should override implementation of the clone() method. Remember that you must make it public and, inside the method, your first action must be super.clone(). Classes that want to allow cloning must implement the marker interface Cloneable. Since the default implementation of Object.clone only performs a shallow copy, classes must also override clone to provide a custom implementation when a deep copy is desired. Basically, if you want to make objects of your class publicly cloneable, you need code like this:

Code: Java
class Test implements Cloneable
{
...
public Object clone()
{
try
{
return super.clone();
}
catch( CloneNotSupportedException e )
{
return null;
}
}
...
}

If you are happy with a protected clone, which just blindly copied the raw bits of the object, you don't need to redefine your own version. However, you will usually want a public one. (Note: You can't create a private or default scope clone; you can only increase the visibility when you override.)

(Continued on next question...)

Other Interview Questions