Fundamentals of Object Cloning in Java
What is Object Cloning?
Object cloning in Java is the process of creating a new object that is an exact replica of an existing object. This is achieved using the clone()
method, which is part of the Object
class in Java. When you clone an object, you create a new instance of the object with the same state (i.e., the same values for its instance variables) as the original object.
Shallow vs. Deep Cloning
There are two types of object cloning in Java: shallow cloning and deep cloning.
Shallow Cloning
In shallow cloning, the new object created is a copy of the original object, but the references to the objects within the original object are still the same. This means that if the original object contains references to other objects, the cloned object will also contain the same references.
public class Person implements Cloneable {
private String name;
private Address address;
// Getters, setters, and other methods
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
In the above example, if you clone a Person
object, the cloned object will have the same Address
object reference as the original object.
Deep Cloning
In deep cloning, the new object created is a complete copy of the original object, including any objects it references. This means that the cloned object has its own copies of all the objects within the original object, and any changes made to the cloned object will not affect the original object.
public class Person implements Cloneable {
private String name;
private Address address;
// Getters, setters, and other methods
@Override
protected Object clone() throws CloneNotSupportedException {
Person clonedPerson = (Person) super.clone();
clonedPerson.address = (Address) address.clone();
return clonedPerson;
}
}
In the above example, the clone()
method of the Person
class performs a deep clone by creating a new Address
object and assigning it to the cloned Person
object.
Implementing Cloning in Java
To implement cloning in Java, a class must implement the Cloneable
interface and override the clone()
method. The Cloneable
interface is a marker interface, which means that it does not have any methods to implement. However, by implementing this interface, you are telling the Java Virtual Machine (JVM) that your class supports cloning.
The clone()
method is defined in the Object
class, but it is protected. To use the clone()
method, you need to override it in your class and make it public.
public class Person implements Cloneable {
private String name;
private Address address;
// Getters, setters, and other methods
@Override
public Person clone() throws CloneNotSupportedException {
return (Person) super.clone();
}
}
In the above example, the Person
class implements the Cloneable
interface and overrides the clone()
method to return a new Person
object.