Middle
What is needed to clone one object into another?
sobes.tech AI
Answer from AI
To clone an object in Java, the typical approach is to implement the Cloneable interface and override the clone() method.
-
Implement
Cloneableinterface: The class should implement the marker interfacejava.lang.Cloneable. This interface has no methods but signals to JVM that the object can be cloned viaObject.clone(). -
Override
clone()method: The class should override the protectedclone()method fromjava.lang.Object. In the implementation, usually callsuper.clone().
class MyClass implements Cloneable {
private int value;
private String name;
public MyClass(int value, String name) {
this.value = value;
this.name = name;
}
// Getters and setters if needed
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "MyClass{" +
"value=" + value +
", name='" + name + '\'' +
'}';
}
public static void main(String[] args) {
try {
MyClass original = new MyClass(10, "Original");
// Clone
MyClass cloned = (MyClass) original.clone();
System.out.println("Original: " + original);
System.out.println("Cloned: " + cloned);
// Changing original object does not affect clone (shallow copy of primitives and String)
original.value = 20;
original.name = "Modified Original";
System.out.println("Modified Original: " + original);
System.out.println("After modification, clone: " + cloned); // remains unchanged
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
The super.clone() method performs shallow copying. This means:
- Primitive fields and
Stringare copied by value. - Reference fields point to the same object (shared reference).
For deep cloning, override clone() and clone each referenced object manually.
Alternative approaches include:
- Copy constructors.
- Factory methods.
- Serialization/deserialization.
- Using libraries (e.g., Apache Commons Lang
SerializationUtils.clone()).