clone() is a method in the Java programming language for object duplication. Because objects in Java are manipulated through reference variables, there is no direct way to copy an object (We would be trying to duplicate the reference variable rather than the object we control through that variable). Therefore, a special clone() method exists in the ultimate superclass Object to provide a standard mechanism for duplicating objects. The class Object's clone() method creates and returns a copy of the object. However, clone() throws a CloneNotSupportedException unless the class you are trying to use it on implements the marker interface Cloneable. The default implementation of Object.clone() performs a shallow copy. Classes must override clone() to provide a custom implementation when a deep copy is desired, or some other custom behavior is desired. The syntax for calling clone in Java is:
Object copy = obj.clone();
or commonly
MyClass copy = (MyClass) obj.clone();
which provides the typecasting needed to assign the generic Object reference returned from clone to a reference to a MyClass object. One disadvantage with the design of the clone() method is that the return type of clone() is Object, and needs to be explicitly cast back into the appropriate type (technically a custom clone() method could return another type of object; but that is generally inadvisable). One advantage of using clone() is that since it is an overridable method, we can call clone() on any object, and it will use the clone() method of its actual class, without the calling code needing to know what that class is (which would be necessary with a copy constructor).


