Java Zero to All All questionsPractise free
Interview questions › Design Patterns in Java › Creational Design Patterns

Someone asks you to 'implement clone()' for an object with a mutable list field. How do you respond?

Level III · MidCreational Design Patterns
Short answer

I'd lead by saying I'd avoid Cloneable and prefer a copy constructor or a static copyOf factory, because Cloneable is a marker with no clone method, Object.clone is protected/native, it bypasses constructors and complicates final fields, and it defaults to shallow copy.

Explanation

The crux is shallow vs deep: a shallow copy shares the list reference so mutating the copy corrupts the original, so I'd deep-copy the mutable field (new ArrayList<>(other.list)). I'd still demonstrate I can write clone() correctly by cloning each mutable field, but frame the copy constructor as the cleaner default.

Common mistakes
  • Implementing clone() and sharing the mutable list.
  • Not offering a copy constructor or static factory instead.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Creational Design Patterns.

Practise free

More on Creational Design Patterns