Q71: What are Shallow Copy versus Deep Copy, and why is Cloneable criticized?

  • Shallow Copy: Copies object field values directly. Primitive values are copied, but object references point to the same shared heap objects.
  • Deep Copy: Recursively duplicates the target object AND all nested child objects, allocating completely independent heap structures.
  • Cloneable Flaws: Marker interface lacking clone method; Object.clone() uses protected native bitwise copying, bypassing constructors. Prefer Copy Constructors or Static Factory Methods.
Key Takeaways
  • Shallow copy shares nested references; Deep copy recursively duplicates object graphs.
  • Prefer Copy Constructors over Cloneable.
Knowledge Check

Why are Copy Constructors preferred over implementing java.lang.Cloneable?