Cloning an object essentially means exact copy of an object. its literal meaning is ‘an identical copy’. In Java, it is supported with the help of Cloneable interface and the clone() method, which guarantees that memory address of both original and cloned object would be different.
Before we go further, lets first understand that Cloneable is a marker or tag interface. A marker interface is the one which has no methods in it. In Java API :
- java.util.RandomAccess (added in Java 1.5)
are marker interfaces (yes, no methods in them !!!)
Implementing the Cloneable Interface
So to clone in Java, one must:
– implement the Cloneable interface and
– must override clone() method which is in java.lang.Object class (not in Cloneable interface)
Lets look at its signature:
Clone() method creates a new object that is a bit-for-bit copy of the source object. There are two safety measures built-in:
1) Being protected, it restricts access from outside the java.lang package.
2) Checks that the object’s class being cloned, implements the ‘Cloneable’ interface, else throws ‘CloneNotSupportedException’.
Default cloning operation is “Shallow” – which means that it does not clone objects that are referenced inside the other objects. It copies the value of data element bit-for-bit, so result being two references sharing the same referred-to object.
If sub-object shared between original and copy is immutable(for ex. String) then it does not matter. But in case of mutable object, you must redefine the clone method to make a ‘deep’ copy.
As shown in the diagram, if you use shallow cloning then the memory address for source and cloned objects are different (e.g. Object A has memory address 100 but Object A_Clone has memory address of 200) but the objects that reside as an attribute of object A points to the same memory location (101) after being cloned to object A_Clone. It means if object A changes the value of its attribute named ‘B’ then the same would be reflected in the cloned object as well. This might not be desirable from a cloned object.
“Deep Copying” creates both a new reference and a new object for the reference to refer to.
Let’s look at a code sample which would provide more clarity about it:
Difference between Copying and Cloning
Quite many times we confuse copying the object to cloning but there is a significant difference. The original and the copy of the object refers to the same object in case we copy the object. Change to either of them, affects both the objects.
But in case of cloning, both the objects are now independent of each other. Changing the property of one does not impact the other one.
Happy Cloning (just like Star Wars):-