Cloning in Java

0
1489

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.lang.Cloneable
  • java.io.Serializable
  • java.util.EventListner
  • 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:

protected native Object clone() throws CloneNotSupportedException

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’.

Shallow Cloning

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.

Shallow clone

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 Cloning

“Deep Copying” creates both a new reference and a new object for the reference to refer to.

Deep clone

Let’s look at a code sample which would provide more clarity about it:

Class Student implements Cloneable {
    
    //immutable variable
    private String studentName;
    //mutable variable
    private Address studentAddress;

    public Student(String studentName, Address studentAddress) {
        this.studentName = studentName;
        this.studentAddress = studentAddress;
    }
    
    @Override
    protected Object clone() {
        try{
            //shallow copy - only for immutable fields - studentName
            Student studentClone = (Student) super.clone();
            
            //Deep Copy for mutable fields - studentAddress
            studentClone.studentAddress = (Address) studentAddress.clone();
            
            return studentClone;
        }catch(CloneNotSupportedException e){ return null; }   
    }
}

Class LetMeClone(){
    public static void main(String[] args) throws CloneNotSupportedException {
    
        Address address = new Address(12, "MyStreet", "MyCity");
        
        Student originalStudent = new Student("Shalini", address);
        
        //Clone of original student
        Student clonedStudent = (Student) originalStudent.clone();
        
     }
}

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.

Code Sample:

Student originalStudent = new Student("Shalini", 50);

/* Example of Copying - where copyStudent would reflect the change in weight in originalStudent as well */
Student copyStudent = originalStudent;
copyStudent.increaseWeight(20); //This would change Original Shalini's weight as well by 20 Kgs

/* Example of Cloning - where cloneStudent would NOT reflect any change in weight to originalStudent */
Student cloneStudent = (Student) originalStudent.clone();
cloneStudent.increaseWeight(20);

 

Happy Cloning (just like Star Wars):-

cloning

Previous articleCollection Interview Questions
Next articleJSP Directives
I have spent almost 10 years playing around Java and related technologies. I love to write on different topics and would be very much willing to hear back your feedback/suggestions on them. This site is a medium to share my knowledge with the Java folks and grow further. My other interests include traveling, driving, swimming and dance. But yes, my web site has become my passion over the time :) I live in Scotland and travel to India often, my roots being there.

NO COMMENTS

LEAVE A REPLY