Sobes.tech
Junior

What do you know about surface copying?

sobes.tech AI

Answer from AI

Shallow copy creates a new object copy but does not copy the objects referenced by the fields of the original object. Instead, it copies the references themselves.

Features:

  • Changes in mutable objects referenced by the copies will be visible in the original object and vice versa.
  • Faster than deep copying for objects with many references.

It is implemented, for example, by the clone() method (if the object implements Cloneable) or manually.

Example of clone():

// Creating a class with a mutable field
class Address {
    String city;

    public Address(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Address{" +
               "city='" + city + '\'' +
               '}';
    }
}

// Creating a class with a reference to Address, implementing Cloneable
class Person implements Cloneable {
    String name;
    Address address;

    public Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    // Implementing shallow copy via Object.clone()
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "Person{" +
               "name='" + name + '\'' +
               ", address=" + address +
               '}';
    }
}

// Usage example
public class ShallowCopyExample {
    public static void main(String[] args) throws CloneNotSupportedException {
        Address originalAddress = new Address("New York");
        Person originalPerson = new Person("Alice", originalAddress);

        // Shallow copy
        Person copiedPerson = (Person) originalPerson.clone();

        System.out.println("Original Person: " + originalPerson);
        System.out.println("Copied Person: " + copiedPerson);

        // Modifying the mutable field in the original's nested object...
        originalAddress.city = "Los Angeles";

        // ...changes are visible in the copy as well, since they reference the same Address object
        System.out.println("\nAfter modifying original address:");
        System.out.println("Original Person: " + originalPerson);
        System.out.println("Copied Person: " + copiedPerson);
    }
}

Used when full duplication of the entire object hierarchy is not necessary, or when nested objects are immutable.

What do you know about surface copying? — Java - sobes.tech