All stories
Java

Shallow Copy

H
hemant-kumar

December 7, 2013

In Shallow copy all the fields are just copied from source object to destination object.

If the source object is containing any field that holds a reference to another object then only the reference will be copied i.e. source and destination objects field(that particular field) will point to same memory location.

Java code for Shallow Copy

package shallow;
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() {
        try {
            return super.clone();
        }
        catch (CloneNotSupportedException e) {
            return null;
        }
    }
   
    @Override
    public String toString()
    {
        return "name: " + name + ", Job Description: " + jobDescription;
    }
}
public class ShallowCopy
{
    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 + "]");
    }
}
Java

0

If you found this helpful, give it some claps!

SHARE THIS ARTICLE

Share on X
LinkedIn

Responses0

Sign in to join the conversation

Sign in