The Art of Cloning in Java: A Practical Approach

Arpit Bhatt
3 min read2 days ago

--

Introduction

Object cloning in Java refers to creating an exact copy of an existing object. This is useful when you need to duplicate an object without affecting the original instance. Java provides a built-in mechanism to achieve cloning through the Cloneable interface and the clone() method.

Cloning Mechanism

Java provides cloning through the java.lang.Cloneable interface and the Object.clone() method. The Cloneable interface is a marker interface (i.e., it does not contain any methods) that allows an object to be cloned.

Steps to Implement Cloning

  1. Implement the Cloneable interface in the class.
  2. Override the clone() method from the Object class.
  3. Handle CloneNotSupportedException.

Example of Shallow Cloning

class Employee implements Cloneable {
int id;
String name;

Employee(int id, String name) {
this.id = id;
this.name = name;
}

@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}

public void display() {
System.out.println("ID: " + id + ", Name: " + name);
}
}

public class CloneExample {
public static void main(String[] args) {
try {
Employee emp1 = new Employee(101, "John Doe");
Employee emp2 = (Employee) emp1.clone();

emp1.display();
emp2.display();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}

Output:

ID: 101, Name: John Doe
ID: 101, Name: John Doe

This demonstrates that emp2 is a cloned copy of emp1.

Deep Cloning

Shallow cloning works fine for primitive and immutable objects, but for objects containing references to other objects, a deep copy is needed.

Example of Deep Cloning

class Address implements Cloneable {
String city;

Address(String city) {
this.city = city;
}

@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Person implements Cloneable {
int id;
String name;
Address address;

Person(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}

@Override
protected Object clone() throws CloneNotSupportedException {
Person cloned = (Person) super.clone();
cloned.address = (Address) address.clone(); // Deep cloning
return cloned;
}

public void display() {
System.out.println("ID: " + id + ", Name: " + name + ", City: " + address.city);
}
}
public class DeepCloneExample {
public static void main(String[] args) {
try {
Address addr1 = new Address("New York");
Person person1 = new Person(201, "Alice", addr1);
Person person2 = (Person) person1.clone();

person1.display();
person2.display();

// Modifying the address of cloned object
person2.address.city = "Los Angeles";

System.out.println("After modifying cloned object's city:");
person1.display();
person2.display();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}

Output:

ID: 201, Name: Alice, City: New York
ID: 201, Name: Alice, City: New York
After modifying cloned object's city:
ID: 201, Name: Alice, City: New York
ID: 201, Name: Alice, City: Los Angeles

Here, deep cloning ensures that modifying the cloned object’s city does not affect the original object.

Alternatives to Cloning

Cloning can sometimes be complex and error-prone. Alternative approaches include:

  1. Copy Constructors: Creating a new object and manually copying attributes.
  2. Serialization and Deserialization: Converting objects to byte streams and back.
  3. Using Third-party Libraries: Libraries like Apache Commons Lang provide utilities for cloning.

Conclusion

Object cloning in Java is a useful technique for duplicating objects. While shallow cloning works well for simple cases, deep cloning is necessary for complex objects. Depending on the use case, alternative approaches may be more suitable.

___

Happy coding!

Follow my Instagram page — Programming_Pulse for daily programming tips and insights!

https://www.instagram.com/programming_pulse/

--

--

Arpit Bhatt
Arpit Bhatt

No responses yet