Suppose you have a picture in the computer, now you want to edit it or experiment on it by applying varies filters, In order to do so, first you create a copy of it and then work on it such that the original picture remain unaffected.
The same is done in OOP as the object cloning.
Object Cloning in OOP
In Object-Oriented Programming (OOP), object cloning refers to the process of creating an exact copy (or duplicate) of an object. Just like photocopying a document, cloning an object means creating a new instance with the same values as the original, without affecting the original object when the clone is modified.
This concept is useful when:
- You want to preserve the state of an object.
- You want to modify a copy without altering the original.
- You’re dealing with prototypes or duplicating templates.
Why Clone an Object?
Consider a scenario where you're designing a game and need to duplicate a character object so that multiple characters start with the same initial attributes. Cloning helps by allowing you to copy a pre-configured object template.
Types of Cloning
1 Shallow Copy
Shallow cloning creates a new object that is a duplicate of the original object but only at the surface level. The new object will have the same values for all primitive fields, and references to the same memory locations for any reference-type fields (e.g., objects, arrays, or collections). This means that while the cloned object is distinct from the original, any modifications to shared references will be reflected in both objects.
- Creates a new object.
- Copies values of all fields.
- If the field is a primitive type, it's copied by value.
- If the field is an object reference, only the reference is copied (both original and clone point to the same sub-object).
2 Deep Copy
Deep cloning ensures that a completely independent copy of the object is created, including all nested objects. This prevents unintended modifications in the original object when the cloned object is modified.
- Creates a new object.
- Copies all fields recursively.
- For object references, it creates new copies of those objects too.
- Original and clone are completely independent.