Sobes.tech
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.

  1. Implement Cloneable interface: The class should implement the marker interface java.lang.Cloneable. This interface has no methods but signals to JVM that the object can be cloned via Object.clone().

  2. Override clone() method: The class should override the protected clone() method from java.lang.Object. In the implementation, usually call super.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 String are 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()).
What is needed to clone one object into another? — Java - sobes.tech