Sunday, April 17, 2011

The clone() method in Java

Clone
Clone method is protected method of object class : protected Object clone() throws CloneNotSupportedException. This method is used to create a copy of an object of a class which implements Cloneable interface. By default it does field-by-field copy as the Object class doesn't have any idea in advance about the members of the particular class whose objects call this method. So, if the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned. But, if the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

Cloneable interface

We get CloneNotSupportedException if we try to call the clone() method on an object of a class which doesn't implement the Cloneable interface. This interface is a marker interface and the implementation of this interface simply indicates that the Object.clone() method can be called on the objects of the implementing class.

Example: how cloning works in Java?

Class A {
...
}
A objA = new A();
A objACloned = (A) objA.clone();

Now, objA != objACloned - this boolean expression will always be true as in any case a new object reference will be created for the cloned copy.

objA.getClass() == objACloned.getClass() - this boolean expression will also be always true as both the original object and the cloned object are instances of the same class (A in this case).

Initially, objA.equals(objACloned) will return true, but any changes to any primitive data type member of any of the objects will cause the expression to return false. It's interesting to note here that any changes to the members of the object referenced by a member of these objects will not cause the expression to return false. Reason being, both the copies are referring to same object as only the object references get copied and not the object themselves. This type of copy is called Shallow Copy (Read - Deep Copy vs Shallow Copy).

No comments:

Post a Comment

Chitika