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
- Implement the
Cloneableinterface. - Override the
clone()method. - 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);
}
}
🔹 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
-
Cloneableis a marker interface (no methods). - If not implemented,
CloneNotSupportedExceptionoccurs. -
clone()method belongs to theObjectclass. - 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)