x

Java – Object Cloning

PREV     NEXT

Object Cloning is the process of creating an exact copy of the object. The clone() method which belongs to the object class, is used for this purpose.


Method Signature:

protected Object clone() throws CloneNotSupportedException

The class whose object’s copy has to be created must implement the marker interface, Cloneable. If the class doesn’t implements the interface and when the clone operation is carried out, then ‘CloneNotSupportedException’ is thrown.

Example:

class Employee implements Cloneable {

The general intent of the clone method for any object x is,

  • clone ! = x;

i.e. The cloned object and the original object will have separate memory address.

  • clone.getClass() == x.getClass();

i.e. The cloned object should have the same class type as that of the original.

  • clone().equals(x);

i.e The cloned object and the original object are equal.


All the above statements will be true but are not the exact requirements.

Shallow Copy Vs. Deep Copy:

  • The default implementation of the clone method is to copy each member of the class to the cloned object.
  • For the fields of primitive type, a completely new copy of the object is created and the reference to the new copy will be returned.
  • If the original class contains any reference type, only the object reference of those members are copied and not the content.
  • Hence the reference type members in both the original and the cloned object refer to the same object.
  • This results in shallow copying. i.e Any change made to the cloned copy would reflect in the original object too.

Deep Copy:

  •  A deep copy copies all the fields including the reference fields and makes a new copy for the cloned object such that both the copies are totally independent. i.e. the changes made in one object are not reflected in the other.
  • All the member classes in original class should support cloning and the clone method of original class should call super.clone() on all member classes.

    PREV     NEXT



Like it? Please Spread the word!