Deep Copy Object Cloning in Java


An alternative is a deep copy, meaning that fields are dereferences: rather than references to objects being copied, new copy objects are created for any referenced objects, and references to these placed in B. The result is different from the result a shallow copy gives in that the objects referenced by the copy B are distinct from those referenced by A, and independent.

Deep copies are more expensive, due to needing to create additional objects, and can be substantially more complicated, due to references possibly forming a complicated graph.

Source Code

//Deep Copy Object Cloning in Java
class Designation
{
    String role;
    @Override
    public String toString() {
        return role;
    }
}
class Employee implements Cloneable
{
    String name;
    int age;
    Designation deg=new Designation();
 
    public void display()
    {
        System.out.println("Name       : "+name);
        System.out.println("Age        : "+age);
        System.out.println("Department : "+deg);
        System.out.println("----------------------");
    }
    public Object clone() throws CloneNotSupportedException
    {
 
        // Assign the shallow copy to new reference variable e
        Employee e = (Employee)super.clone();
 
        // Creating a deep copy for deg (Designation)
        e.deg = new Designation();
        e.deg.role = deg.role;
 
        // Create a new object for the field e
        // and assign it to shallow copy obtained,
        // to make it a deep copy
        return e;
    }
 
 
}
public class objectCloningDeepDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
 
        Employee e1 =new Employee();
        e1.name="Ram Kumar";
        e1.age=25;
        e1.deg.role="Manager";
        System.out.println("Before Changing Role : ");
        e1.display();
 
        System.out.println("Cloning and Printing E2 object : ");
        Employee e2 = (Employee)e1.clone();
        e2.deg.role="HR";
        e2.display();
 
        System.out.println("After Changing Role : ");
        e1.display();
 
    }
}
 

Output

Before Changing Role :
Name       : Ram Kumar
Age        : 25
Department : Manager
----------------------
Cloning and Printing E2 object :
Name       : Ram Kumar
Age        : 25
Department : HR
----------------------
After Changing Role :
Name       : Ram Kumar
Age        : 25
Department : Manager
----------------------
To download raw file Click Here

Basic Programs