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.
Yes.
But first you need that your class will implement Cloneable and throw exception
Output: true
The default
Object.clone()
is indeed a shallow copy. However, it's designed to throw aCloneNotSupportedException
unless your object implementsCloneable
.And when you implement
Cloneable
, you should overrideclone()
to make it do a deep copy, by callingclone()
on all fields that are themselves cloneable.