![]() |
VOOZH | about |
The default version of the clone method creates a shallow copy of an object. In java being object-oriented, object copying is creating a copy of the existing object, so the object copied can be a similar copy of the exact copy of the object of which it is copied. There are 2 ways to copy an object as follows:
In C/C++ there
Methods of Copying
Now, copying can be of three types as follows:
Generally, deep copy and cloning is referred to as the same deep cloning as the difference between them is a thin line where focus is laid to ease for copying objects manually using the clone() method.
👁 Image1. Shallow Copy/ Cloning
Illustration: Shallow copying object 't2'
class GFG
{
int i,j;
}
main(String[] args)
{
// Copying
GFG object1 = new GFG() ;
object.i = 5;
object.j = 6;
GFG object2 = object1 ; // shallow copying object
} 👁 ImageExample 1
Output: False if Deepcopy & True if shallow : true
Output explanation:
2. Deep copy/ cloning is the process of creating exactly the independent duplicate objects in the heap memory and manually assigning the values of the second object where values are supposed to be copied is called deep cloning.
GFG object1 = new GFG() ; || Creating object of GFG class object.i = 5; object.j = 6; GFG object2 = new GFG; || Creating another object class object2.i = object1.i ; || Deep copying object2.j = object1.j ; || Deep copying
👁 ImageNote: In can not directly call clone() method using object.clone() as clone method in Object class of java is protected. So override the function by making access modifier as public in return super.clone() from the class created to override
Example 2
false
Output explanation: