![]() |
VOOZH | about |
Object cloning in Java is the process of creating an exact copy of an existing object. The clone() method, defined in the Object class, is used to perform cloning and create a new object with the same state as the original object.
class MyClass implements Cloneable {
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Example: Program to demonstrate object cloning using the clone() method
o1: 10 20 o2: 10 20
Explanation: The object o1 is cloned using the clone() method, creating a new object o2 with the same field values. Although both objects contain identical data, they occupy different memory locations.
Example: Program to demonstrate object cloning (shallow copy)
Original: GFG{name:'Ram', age:24}
Cloned: GFG{name:'Ram', age:24}
Explanation: In the above example, the clone() method is overridden in the GFG class to perform a shallow copy of the object. This creates a new object "p2" with the same values as the original object "p1", but changes to immutable fields like String do not affect each other.
Example: Program to demonstrate deep copy using clone()
10 20 30 40 100 20 300 40
Explanation: In the above example, we can see that a new object for the Test class has been assigned to copy an object that will be returned to the clone method. Due to this, t3 will obtain a deep copy of the object t1. So any changes made in the ācā object fields by t3, will not be reflected in t1.
| Feature | Shallow Copy | Deep Copy |
|---|---|---|
| Object Creation | New object created | New object created |
| Referenced Objects | Shared between copies | Independently copied |
| Memory Usage | Less | More |
| Performance | Faster | Slower |
| Data Independence | Lower | Higher |
Note: We can use the Assignment Operator to create a copy of the reference variable. This creates a shallow copy, means both variables will refer to the same object in memory. This is not the same as cloning, where a new object is created.