Interview Questions

How the copy works with clone() method?

Java Interview Questions for Cloning and Cloneable


(Continued from previous question...)

How the copy works with clone() method?

The copying of the orignial object to clone object does the following
* Primitive type fields: For primitive types the value of the member fields are copied.
* Object type fields: For object types, by default it does a shallow copy (ie) only the reference is copied. With this object filed members of both the original object and the copied objects will have references pointing to the same object. That means, in the above example, if the dateOfBirth variable is changed for either the original person or the copy, this will get reflected for both the persons.

If you want to do a deep copy (where even the values of the object fields are copied and the reference will point to different objects), you have to override the clone method with custom cloning operation after invoking the super.clone().

(Continued on next question...)

Other Interview Questions