Shallow and deep cloning in Java
Difference between shallow and deep cloning
Shallow Copy copies as little information about an object as possible. By default, Java cloning is shallow, i.e. the Object class is unaware of the structure of the class it is copying. Cloning of this type is carried out by the JVM according to the following rules:
- If the class has only members of primitive types, then a completely new copy of the object will be created and a reference to that object will be returned.
- If a class, in addition to members of primitive types, contains members of reference types, then references to objects of these classes are copied. Hence, both objects will have the same references.
Deep copying duplicates absolutely all object information:
- There is no need to copy primitive data separately;
- All reference type members in the original class must support cloning. For each such member, super.clone() must be called when overriding clone();
- If any member of the class does not support cloning, then in the cloning method you need to create a new instance of this class and copy each of its members with all the attributes into a new class object, one by one.
Preferred method of cloning
The safest, and therefore preferred, way to clone is to use a specialized copy constructor:
- No inheritance errors (no need to worry that inheritors will have new fields that will not be cloned through the clone() method);
- Clone fields are specified explicitly;
- Even final fields can be cloned.
Why is the clone() method declared in the Object class and not in the Cloneable interface?
The clone() method is declared in the Object class with the native modifier to provide access to the standard shallow copying of objects. At the same time, it is declared as protected, so that this method cannot be called on objects that have not overridden it. The Cloneable interface itself is a marker (does not contain method declarations) and is only needed to indicate the very fact that this object is ready to be cloned. Calling the overridden clone() method on a non-Cloneable object will throw a CloneNotSupportedException.
Read also:
Comments
Post a Comment