Sobes.tech
Junior — Middle

What object copying methods in Java do you know?

sobes.tech AI

Answer from AI

In Java, there are two main ways to copy objects:

  1. Shallow copy — copies only primitive fields and references to objects, not the objects themselves. The referenced objects are shared between the original and the copy. Usually implemented via the clone() method from the Cloneable interface.

  2. Deep copy — creates a full independent clone of the object, including all nested objects. This often involves writing custom copy methods or using serialization/deserialization.

Example of shallow copy using clone():

class Person implements Cloneable {
    String name;
    int age;

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

For deep copying, you might implement a method that manually copies all fields, creating new objects for nested references.

What object copying methods in Java do you know? — Java - sobes.tech