Home » Core Java » Object Cloning in Java

Object Cloning in Java

 
What is Object Cloning :: 

1. Object cloning means to create exact copy of an object of a class.

2. Actual object and cloned object are two different objects in Java heap memory

3. Object Cloning is achieved by using clone() method of Object class.  

4. clone() is a method to create and return a copy of the object.

Properties :
1 : clone object and actual object are two separate objects in Java heap.For any object “obj” obj.clone() != obj; will return true;
2 : getClass() method called on actual object and cloned object should return the same class.For any object “obj “obj.clone().getClass()=obj.getClass(); will return true.
3 : clone object and actual object are equal by values.For any object “obj” obj.clone.equals(obj); will return true;
4 : A class must implement java.lang.Cloneable interface to clone its objects else CloneNotSupportedException will be thrown.
5 : Constructor is not called during cloning of Object in Java.
6 : Shallow cloning is default cloning.

Syntax :

Advantages :
1 : Suppose we create two instance of a class Example
Example obj1 = new Example();
Example obj2 = new Example ();
obj1 = obj2;
Any changes in obj2 will reflect on obj1 ,but any changes in obj1 will not reflect in obj2.But if we do obj2 =obj1.clone(); , any changes in obj2 will reflect on obj1 and vice versa.
2 : Clone object creation is faster than object creation using new operator.

Types of Cloning :
1 : Shallow Cloning
2 : Deep cloning


Leave a comment

Your email address will not be published. Required fields are marked *

fifteen + 10 =