Sobes.tech
Junior — Middle

Explain the concept of shallow copying an object and its features.

sobes.tech AI

Answer from AI

Shallow copying of an object in Java creates a new object, but the object fields inside are not fully copied, only references to them are copied. That is, nested objects are not duplicated, but remain shared between the original and the copy.

Features of shallow copying:

  • Fast creation of an object copy.
  • Changes in nested objects will be visible in both the original and the copy, as they refer to the same objects.
  • Suitable if the object contains only primitive types or if nested objects are not modified.

Example of shallow copying using the clone() method:

class Person implements Cloneable {
    String name;
    Address address; // nested object

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

class Address {
    String city;
}

// When cloning Person, a new Person object is created, but the address field will refer to the same Address object.

If a completely independent copy is needed, deep copying is used.

Explain the concept of shallow copying an object and… - sobes.tech