I am new to java can some one tell me please. Is it
Shallow copy
: primitive types and references are copied
Deep copy
: objects are copied recursively
There is no default implementation for clone()
Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. Using Assignment Operator to create a copy of the reference variable.
Shallow Cloning It is the default cloning process in Java where a shallow copy of the original object will be created with exact field. In case the original object has references to some other objects as fields, then only the references of that object will be cloned instead of new object creation.
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.
The clone() is protected because it is not declared in the Cloneable interface. Because of this reason, the clone method becomes somewhat useless as it might make the copies of your existing data.
You can look at the documentation for clone()
:
The method
clone
for classObject
performs a specific cloning operation. First, if the class of this object does not implement the interfaceCloneable
, then aCloneNotSupportedException
is thrown. Note that all arrays are considered to implement the interfaceCloneable
and that the return type of the clone method of an array typeT[]
isT[]
whereT
is any reference or primitive type. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With