Tuesday 17 January 2017

Types of Cloning

Clone method
If a class, or one of its superclasses, implements the Cloneable interface, you can use the clone() method to create a copy from an existing object. To create a clone, you write:
aCloneableObject.clone();
Object's implementation of this method checks to see whether the object on which clone() was invoked implements the Cloneable interface. If the object does not, the method throws a CloneNotSupportedException exception.
public Object clone() throws CloneNotSupportedException

Types of Cloning
Shallow Cloningit is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same subobjects. By default shallow copy is used in Java. Shallow clone only copies the top level structure of the object not the lower levels.
If  a = clone(b) , then b.equals(a)

Deep CloningDeep copy is a complete duplicate copy of an object. If an object has references to other objects, complete new copies of those objects are also made. A deep copy generates a copy not only of the primitive values of the original object, but copies of all subobjects as well, all the way to the bottom. If you need a true, complete copy of the original object, then you will need to implement a full deep copy for the object.

No comments:

Post a Comment