Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › OOP I — Classes, Objects, Constructors

What is the difference between shallow and deep copying, and how does it interact with a copy constructor?

Level II · JuniorOOP I — Classes, Objects, Constructors
Short answer

A shallow copy duplicates the top-level object but shares references to nested mutable objects, so mutating a nested list affects both copies; a deep copy recursively clones the nested objects so they are fully independent.

Explanation

A copy constructor must deep-copy any mutable fields (lists, dates, arrays) or it silently produces aliasing bugs. In practice I prefer copy constructors or static 'copyOf' factories over Cloneable, since clone() is broken by design (no constructor call, shallow by default, awkward checked exception).

Common mistakes
  • Thinking a copy constructor automatically deep-copies nested objects.
  • Sharing mutable collections between the original and the copy.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for OOP I — Classes, Objects, Constructors.

Practise free

More on OOP I — Classes, Objects, Constructors