Is clone() in java shallow copy?

Josh Morrison picture Josh Morrison · Mar 11, 2011 · Viewed 12.6k times · Source

Is clone() in java a shallow copy?

Eventually this gets to the clone() method of Object (the uppermost class), which creates a new instance of the same class as the object and copies all the fields to the new instance (a "shallow copy").

I read this from wikipedia.

I don't understand why it is a shallow copy. clone() will create a new instance with all fields. Is this just a deep copy? confused. Need some explanation for me.

Answer

Chris Jester-Young picture Chris Jester-Young · Mar 12, 2011

The default Object.clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable.

And when you implement Cloneable, you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.