Deep copy means whenever you create an copy of an object it should be a complete disjoint object. Which means if I modify some attribute of one object it should not affect the attribute of other object.
Shallow copies are not completely disjoint objects. Changes made in one object will be seen in the other copied object.
Basically, if your class has primitive attribute it doesn’t create any problem while making copy. The problem is if your class has any derived class attribute.
How to make a copy of an object ?
Cloning is one of the way.
Lets see with an example.
class Department { int deptId; String deptName; //Add setters and getters here public Department(int deptId, String deptName) { this.deptId=deptId; this.deptName=deptName; } }
class Employee implements Cloneable{ int age; String name; Department department;//Derived class //Add setters and getters here public Employee(int age, String name, Department department) { this.age=age; this.name=name; this.department=department; } protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
In some client class:
Department dept=new Department(1,"Delivery"); Employee original=new Employee(44,"Prasanna",dept); Employee cloned=(Employee)original.clone(); //cloned.setDepartment(new Department(2,"HR")); //This will not given the desired result. cloned.getDepartment().setDeptName("HR"); System.out.println(original.getDepartment().getDeptName()); System.out.println(cloned.getDepartment().getDeptName());
If you run the above client class, the output will be:
HR HR
So as we can see the changes made in the cloned object also affects the original object.
Now lets make some changes so that it will be a deep copy.
- Add clone() in Department class.
- Change the clone() in Employee class in a different way as shown below.
class Department implements Cloneable{ int deptId; String deptName; //Add setters and getters here public Department(int deptId, String deptName) { this.deptId=deptId; this.deptName=deptName; } protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
class Employee implements Cloneable{ int age; String name; Department department; //Add setters and getters here public Employee(int age, String name, Department department) { this.age=age; this.name=name; this.department=department; } protected Object clone() throws CloneNotSupportedException { //return super.clone(); Employee employee=(Employee)super.clone(); employee.department=(Department)department.clone(); return employee; } }
Now if you run the client class, below would be the output:
Delivery HR
That means now its working, we are getting disjoint objects.