Deep Copy & Shallow
Deep Copy & Shallow
Copy
Copy Constructor
• An overloaded constructor.
• When an object is passed to a function, a bitwise (exact)
copy of that object is made and given to the function.
• If the object contains a pointer to allocated memory, the
copy will point to the memory as does the original object.
Copy Constructor (Cont..)
• If the copy makes a change to the contents of this
memory, it will be changed for the original object too.
• Also, when the function terminates, the copy will be
destroyed, causing its destructor to be called.
• That can free dynamically allocated memory, used by the
original object as well.
Shallow Copy
• clone() method of the object class supports a shallow copy of the
object.
• Whenever we use the default implementation of the clone method we
get a shallow copy of the object means it creates a new instance and
copies all the field of the object to that new instance and returns it as
an object type, we need to explicitly cast it back to our original object.
This is a shallow copy of the object.
• If only primitive data type fields or Immutable objects are there, then
there is no difference between shallow and deep copy in Java, That’s
why the name shallow copy or shallow cloning in Java.
Shallow Copy - Example
• public class Person {
private Name name;
private Address address;
public Person(Person originalPerson) {
this.name = originalPerson.name;
this.address = originalPerson.address;
}
[…]
}
Deep Copy