Deep Copy

In Deep copy all the fields are deeply copied from source object to destination object.

If the source object is containing any field that holds a reference to another object then for the destination object a new copy will be created i.e. source and destination objects field will point to different memory location.

Java code for Deep Copy

package deep;
class JobDescription
{
    private String designation;

    public JobDescription(String designation) {
        this.designation = designation;
    }
    public String getDesignation() {
        return designation;
    }
    public void setDesignation(String designation) {
        this.designation = designation;
    }
    @Override
    public String toString() {
        return designation;
    }
}
class Employee implements Cloneable
{
    private String name;
    private JobDescription jobDescription;
   
    public void setName(String name)
    {
        this.name = name;
    }
    public JobDescription getJobDescription() {
        return jobDescription;
    }

    public Employee(String name,String designation)
    {
        this.name = name;
        this.jobDescription = new JobDescription(designation);
    }
   
    public Object clone() {
        Employee employee = new Employee(name,jobDescription.getDesignation());
        return employee;
    }
   
    @Override
    public String toString()
    {
        return "name: " + name + ", Job Description: " + jobDescription;
    }
}
public class DeepCopy
{
    public static void main(String[] args)
    {
        Employee origEmployee = new Employee("John","Manager");
        System.out.println("Original                [" + origEmployee + "]");
        Employee cloneEmployee = (Employee)origEmployee.clone();
        System.out.println("Clone                   [" + cloneEmployee + "]");
        origEmployee.setName("Rose");
        origEmployee.getJobDescription().setDesignation("Worker");
        System.out.println("Original after change   [" + origEmployee + "]");
        System.out.println("Cloned after change     [" + cloneEmployee + "]");
    }
}

Comments

Popular posts from this blog

Index MySQL datadase table in Solr

Hibernate Sharding Example

Shallow Copy