Bird
Raised Fist0

Which approach best guarantees this behavior?

easy🔍 Pattern Recognition Q11 of Q15
OOP & Design Patterns - Prototype Pattern - Deep Copy vs Shallow Copy
You have an object with nested mutable fields, and you need to create a new object instance such that changes to the nested fields in the new object do not affect the original. Which approach best guarantees this behavior?
AManually copy only the top-level fields, sharing nested references to save memory
BUse a greedy algorithm to selectively copy fields based on usage frequency
CSerialize the object to JSON and deserialize it back to create a new instance
DRecursively copy all nested objects to create independent duplicates
Step-by-Step Solution
  1. Step 1: Understand the problem requirement

    The goal is to create a new object where nested mutable fields are independent, so changes in the copy do not affect the original.
  2. Step 2: Evaluate approaches

    Manual shallow copy (A) shares nested references, causing side effects. Greedy selective copying (B) is not a standard approach and risks missing nested objects. JSON serialization (D) can lose methods and fail on special objects. Recursive deep copy (C) ensures all nested objects are duplicated, preserving independence.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Deep copy duplicates nested objects -> no shared references [OK]
Quick Trick: Deep copy duplicates nested objects fully [OK]
Common Mistakes:
MISTAKES
  • Assuming shallow copy suffices for nested mutable fields
Trap Explanation:
PITFALL
  • Shallow copy looks simpler and faster but fails when nested objects are mutable and shared.
Interviewer Note:
CONTEXT
  • Tests if candidate understands difference between shallow and deep copy in object cloning.
Master "Prototype Pattern - Deep Copy vs Shallow Copy" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes