Sobes.tech
Junior — Senior

Implementation of deep copy of Customer object

livecode

Task condition

The task is to implement the clone() method in the Customer class, which will create a full (deep) copy of the given object.

Requirements:

  1. The cloned object should not reference the same nested instances (Address, List<CellNumber>) as the original.
  2. All nested structures within Customer should be independent copies.
  3. After cloning, the equals() method should return true, but references to nested objects should point to different instances.
package com.jetbulb.interviews;

import java.util.Collections;
import java.util.List;

public class JetbulbInterview {
    public static void main(String[] args) {
        Customer customer = new Customer(
                "123",
                66,
                new Address(1, "Street"),
                Collections.singletonList(new CellNumber("777-555-666", 3.14D))
        );

        Customer clonedCustomer = customer.clone();

        System.out.println(customer.equals(clonedCustomer)); // true
        System.out.println(customer == clonedCustomer); // false
        System.out.println(customer.address == clonedCustomer.address); // false
        System.out.println(customer.number == clonedCustomer.number); // false
    }
}

class Customer implements Cloneable {
    String id;
    int age;
    Address address;
    List<CellNumber> number;
}

class Address implements Cloneable {
    int id;
    String name;
}

class CellNumber implements Cloneable {
    String number;
    double coverage;
}