*** Welcome to piglix ***

Clone (Java method)


clone() is a method in the Java programming language for object duplication. In Java, objects are manipulated through reference variables, and there is no operator for copying an object—the assignment operator duplicates the reference, not the object. The clone() method provides this missing functionality.

Classes that want copying functionality must implement some method to do so. To a certain extent that function is provided by "Object.clone()".

clone() acts like a copy constructor. Typically it calls the clone() method of its superclass to obtain the copy, etc. until it eventually reaches Object's clone() method. The special clone() method in the base class Object provides a standard mechanism for duplicating objects.

The class Object's clone() method creates and returns a copy of the object, with the same class and with all the fields having the same values. However, Object.clone() throws a CloneNotSupportedException unless the object is an instance of a class that implements the marker interface Cloneable.

The default implementation of Object.clone() performs a shallow copy. When a class desires a deep copy or some other custom behavior, they must perform that in their own clone() method after they obtain the copy from the superclass.

The syntax for calling clone in Java is (assuming obj is a variable of a class type that has a public clone() method):

or commonly

which provides the typecasting needed to assign the general 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. However, overriding clone() to return the appropriate type is preferable and eliminates the need for casting in the client (using covariant return types, since J2SE 5.0).


...
Wikipedia

...