I am learning how to clone serializable object. When I see the code I got confused that why we need to first serialize the object and then deserialize it ? Is it due to we want to get an Object
(or any other reason) ? Then why we just not return the object, or serialize the object ?
public static Object clone(Serializable object) {
return deserialize(serialize(object));
}
The (simple) clone() method of Object performs a shallow copy of an object. This means that primitive fields are copied, but objects within the cloned object are not copied. Rather, the references within the new object point to the objects referenced by the original object. This can sometimes lead to unexpected results. Sometimes a deep copy of an object is needed. In a deep copy, rather than references in the new object pointing to the same objects as the original class, the references point to new objects (whose values have been copied over).
That's why for deep cloning we first serialize (to copy primitive and non-primitive type objects) and then deserialize (to get and return object from bytes) the object so that we get everything within the object not just primitive type.