clone (Java method)
clone()
is a method in the Java programming language for object duplication.
Because objects in Java are referred to using reference types, there is no direct way to copy the contents of an object into a new object. Assignment of one reference to another merely creates another reference to the same object. Therefore, a special clone()
method exists for all reference types in order to provide a standard mechanism for an object to make a copy of itself.
The Java class Object
contains a clone()
method that creates and returns a copy of the object. By default, classes in Java do not support cloning and the default implementation of clone
throws a CloneNotSupportedException
. Classes wishing 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.
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.