Java Cloning concept explained in detail

Clone (κλών) is a Greek word meaning “branch”, referring to the process whereby a new plant can be created from a twig. In biology it is about copying the DNAs. In Programming action of copying the attributes of one object into another of same data type is called object copy or Cloning. The main object from which we clone could be thought of as “Breeder” which might have several shallow or deep copies/replicas. Cloning is used where we need to save a lot of time and trouble of creating object by new keyword and then initializing/processing them to attain similar object state. With cloning new object with similar object states comes out of the box by virtue of clone() method defined in Object class of javaSmile 

I have an object called as Employee which has below fields :
cloning

Now if we need to construct several objects of similar type either we can use new operator and initialize each object or we can just use the clone method (provided by Object class – mother of all objects). By virtue of cloning, newly created object from clone will have all the values copied –  the object reference of Department, salary account and even id – oops Winking smile this copy is called as shallow copy. Actually department is ok, but id and provident funds account should be entirely new/different for each employee. So the to modify or create a new object which does not blindly copy object reference and values, rather has their own object graph we use Deep copy Smile . Visit this github link to have a look at the code.

https://github.com/premaseem/javaConcepts/commit/d19658a96d1adbbdc81a71661fcf13771d66d393

How will you achieve cloning in java?

In Java everything is achieved through class, object and interface .By default no Java class support cloning but Java provide one interface called Cloneable, which is a marker interface and by implementing this interface we can make duplicate copy of our object by calling clone() method of java.lang.Object class. This Method is protected inside the object class and Cloneable interface is a marker interface and this method also throw  CloneNotSupportedExceptionif we have not implement this interface and try to call clone() method of Object class. By default any clone() method gives shallow copy of the object i.e. if we invoke super. clone() then it’s a shallow copy but if we want to deep copy we have to override theclone() method and make it public and give own definition of making copy of object. Now we let’s see what is shallow and deep copy of object in Java programming language.

Shallow Copy

Whenever we use default implementation of clone method we get shallow copy of object means it create new instance and copy all the field of object to that new instance and return it as object type we need to explicitly cast it back to our original object. This is shallow copy of the object. clone() method of the object class support shallow copy of the object. If the object contains primitive as well as non primitive or reference type variable In shallow copy, the cloned object also refers to the same object to which the original object refers as only the object references gets copied and not the referred objects themselves. That’s why the name shallow copy or shallow cloning in Java. If only primitive type fields or Immutable objects are there then there is no difference between shallow and deep copy in Java.

In shallow copy, a new object is created which contains the exact copy of the values in the original object. Shallow copy follows the bit-wise copy approach. In shallow copy if the field is a memory address, then the address is copied. Thus if the address is changed by one object, the change gets reflected everywhere.

shallowClone

Figure 1: The flow chart describes shallow copy

In this figure, the object – mainObj1 has fields field1 of a primitive type say int, and an object of type String When we do a shallow copy of mainObj1, mainObj2 is created with field2 of type int which contains the copied value of field1 but the String object in mainObj2 – still points to objStr itself. Since field1 is a primitive data type, the value of it is copied into field2. But since objStr is an object, mainObj2 is pointing to the same address of objStr. So any changes made to objStr via mainObj1 get reflected in mainObj2.

Deep Copy

Whenever we need a non shared object graph for newly cloned object we do deep cloning. This can be done in multiple ways while doing overriding clone() we can add our logic for new assignments to the object reference or we have to ensure that all the member class also implement Cloneable interface and override the clone() method of the object class.

In deep copy, not only all the fields of an object are copied, all the dynamically allocated memory address which are pointed by that object are also copied.

DeepCopy04

Figure 2: The diagram describes deep copy process

In this figure, the object mainObj1 has fields field1 a primitive data type say int, and an object of type String When we do a deep copy of mainObj1, mainObj2 is created with field2 containing the copied value of field1 and objStr2 is created which contains the copied value of objStr1 So any changes made to objStr1 in mainObj1 will not reflect in mainObj2.

Lazy Copy

A lazy copy can be defined as a combination of both shallow copy and deep copy. The mechanism follows a simple approach – at the initial state, shallow copy approach is used. A counter is also used to keep a track on how many objects share the data. When the program wants to modify the original object, it checks whether the object is shared or not. If the object is shared, then the deep copy mechanism is initiated.

 

Difference between Shallow and Deep Copy in Java

I think now we know what is deep and shallow copy of object in Java, let see some difference between them so that we can get some more clarity on them.

  • When we call Object.clone(), this method performs a shallow copy of object, by copying data field by field, and if we override this method and by convention first call super.clone(), and then modify some fields to “deep” copy, then we get deep copy of object. This modification is done to ensure that original and cloned object are independent to each other.
  • In shallow copy main or parent object is copied, but they share same fields or children if fields are modified in one parent object other parent fields have automatic same changes occur,but in deep copy this is not the case.
  • If our parent object contains only primitive value then shallow copy is good for making clone of any object because in new object value is copied but if parent object contains any other object then only reference value is copied in new parent object and both will point to same object so in that case according to our need we can go for deep copy.
  • Deep copy is expensive as compare to shallow copy in terms of object creation, because it involves recursive copying of data from other mutable objects, which is part of original object.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s