← Back to libraryQuestion 21 of 273
JavaIntermediate

Cloning: Shallow vs Deep

📖 Detailed Explanation:

Cloning creates a copy of an object. Shallow Copy copies the object and primitives but points to the SAME internal objects. Deep Copy creates copies of those internal objects as well, making the copy entirely independent. The choice depends on your use case.

🌍 Real-World Example:

Shallow Copy: You copy a folder's shortcuts—both versions still point to the same files. Deep Copy: You copy the actual files into a new folder; they are now independent.

🎯 Scenario-Based Interview Question:

If you have a Class 'Employee' containing an 'Address' object, and you perform a shallow clone of Employee, what happens if you change the City in the cloned Employee's Address?