InterviewSolution
| 1. |
Shallow and Deep copy in Java |
|
Answer» Shallow copy and deep copy are related to the cloning PROCESS i.e. creating a copy of an object in Java. Details about the shallow and deep copy are given as follows: Shallow Copy in Java A shallow copy of an object is able to copy the main object but not the inner objects. This means that the original object the created copy shares the inner objects. An example of this is given as follows: public class Employee { private Name name; private DepartmentDetails dept; public Employee(Employee emp) { this.name = emp.name; this.dept = emp.dept; } . . . }In the above example, if a shallow copy is created of an object of class Employee, then a SECOND Employee is created but the Name and DepartmentDetails objects are shared by both the objects. So if CHANGES are made to one of the objects, then they be reflected in the object created using a shallow copy. Deep Copy in Java The deep copy of an object is a fully independent copy and the WHOLE object structure is copied when a new deep copy is created. An example of this is given as follows: public class Employee { private Name name; private DepartmentDetails dept; public Employee(Employee emp) { this.name = emp.name; this.dept = emp.dept; } . . . }In the above example, if a deep copy is created of an object of class Employee then the whole object structure is copied and if changes are made to one of the objects, then they would not be reflected in the object created using a deep copy. |
|