Deep Copy and Shallow Copy
Deep Copy and Shallow Copy
Programming - Java
Instructor: Afifa Hameed
Copy Constructor
• In Java, a copy constructor is a special type of constructor that creates an object using
another object of the same Java class. It returns a duplicate copy of an existing object of
the class.
• We can assign a value to the final field but the same cannot be done while using the
clone() method. It is used if we want to create a deep copy of an existing object. It is
easier to implement in comparison to the clone() method.
• The primary use case of a copy constructor is to create a new object with the same
state as an existing object. It is particularly useful in scenarios where we need to
duplicate an object while maintaining its integrity. By leveraging a copy constructor, we
ensure that the new object is independent of the original one, thereby preventing
unintended side effects that might occur with shallow copying.
Use of Copy Constructor
• Copy constructors allow developers to choose between deep and shallow copying
strategies based on the requirements of the application.
• While shallow copying may suffice for simple objects with primitive fields, deep
copying is essential for preserving the integrity of complex objects with
references to mutable state.
Shallow Copy in Java
• When we do a copy of some entity to create two or more than two
entities such that changes in one entity are reflected in the other
entities as well, then we can say we have done a shallow copy.
• In shallow copy, new memory allocation never happens for the other
entities, and the only reference is copied to the other entities.
Shallow Copy Example
Output of Shallow Copy
Deep Copy
Output of Deep Copy
Array of objects in Java
• We know that an array is a collection of the same data type that
dynamically creates objects and can have elements of primitive types.
• Java allows us to store objects in an array.
• In Java, the class is also a user-defined data type.
• An array that contains class type elements are known as an array of
objects.
• It stores the reference variable of the object.
Array of objects illustration
Creating an Array of Objects
• Deep Copy: For deep cloning, you must override the clone() method
and implement custom logic to copy all referenced objects.
Home task!
• Explore the Java Clone() method.