DEV Community

Gowtham Kalyan
Gowtham Kalyan

Posted on

What is object cloning in Java?

What is Object Cloning in Java?

Object Cloning in Java is a process of creating an exact copy of an existing object. Instead of creating a new object manually and assigning values one by one, cloning allows you to duplicate an object easily.

Java provides cloning support using the Cloneable interface and the clone() method.


🔹 Why Object Cloning is Used

  • To create duplicate objects quickly
  • Improves performance compared to manual copying
  • Useful in real-time applications where object copies are frequently required
  • Helps preserve original object data

🔹 Steps to Perform Object Cloning

  1. Implement the Cloneable interface.
  2. Override the clone() method.
  3. Call clone() using the original object.

🔹 Example

java id="j9mz3x"
class Student implements Cloneable {
    int id;
    String name;

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

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class Test {
    public static void main(String[] args) throws Exception {
        Student s1 = new Student(101, "Rahul");
        Student s2 = (Student) s1.clone();

        System.out.println(s1.name);
        System.out.println(s2.name);
    }
}
Enter fullscreen mode Exit fullscreen mode

🔹 Types of Cloning

1. Shallow Copy

  • Copies object references.
  • Changes in referenced objects affect both copies.

2. Deep Copy

  • Creates a completely independent copy.
  • Changes in one object do not affect the other.

🔹 Important Points

  • Cloneable is a marker interface (no methods).
  • If not implemented, CloneNotSupportedException occurs.
  • clone() method belongs to the Object class.
  • Modern Java often prefers copy constructors or factory methods instead of cloning.

✅ Promotional Content

To understand advanced Java concepts like object cloning, memory management, JVM internals, and real-time application development through practical projects, join the Top Java Real Time Projects Online Training in Ameerpet.

Top comments (0)