Sobes.tech
Junior — Middle

How is an exact copy of an object created in Java?

sobes.tech AI

Answer from AI

In Java, creating an exact copy of an object is usually done using the clone() method, which is defined in the Object class. To allow an object to be cloned, the class must implement the Cloneable interface and override the clone() method. The clone() method creates a shallow copy, meaning it copies the object's fields, but if the fields are references to other objects, only the references are copied, not the objects themselves.

If a deep copy is needed, you must manually implement copying of nested objects within the clone() method or use other approaches, such as serialization.

Example of shallow cloning:

class Person implements Cloneable {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

// Usage:
Person p1 = new Person("Ivan", 30);
Person p2 = (Person) p1.clone();

If the class contains mutable object fields, deep copying requires manually cloning these fields inside clone().