Sobes.tech
Middle

What is a copy constructor?

sobes.tech AI

Answer from AI

The copy constructor is a special constructor of a class that creates a new object by copying the values of the fields from an existing object of the same class. It is used for deep copying when it is necessary to create an independent copy of an object, including all reference fields.

Example:

public class MyClass {
    private int value;
    private List<String> data;

    // Copy constructor
    public MyClass(MyClass other) {
        this.value = other.value; // Copying primitive type
        this.data = new ArrayList<>(other.data); // Deep copying the list
    }

    // Regular constructor
    public MyClass(int value, List<String> data) {
        this.value = value;
        this.data = new ArrayList<>(data);
    }

    // Getters and setters...

    public static void main(String[] args) {
        List<String> originalData = new ArrayList<>();
        originalData.add("item1");
        originalData.add("item2");

        MyClass original = new MyClass(10, originalData);
        MyClass copy = new MyClass(original); // Using copy constructor

        System.out.println("Original value: " + original.value + ", data: " + original.data);
        System.out.println("Copy value: " + copy.value + ", data: " + copy.data);

        // Changing the copy does not affect the original
        copy.data.add("item3");
        System.out.println("Original data after modification: " + original.data);
        System.out.println("Copy data after modification: " + copy.data);
    }
}

Difference from shallow copying (for example, via Object.clone() by default or simple reference assignment):

  • Shallow copying: Only the values of primitive fields and references to objects are copied. The objects referenced by the fields remain shared between the original and the copy. Changes in one object will reflect in the other.
  • Deep copying: A new object is created, and all nested objects referenced by the fields are recursively copied. The original and the copy are fully independent. Changes in one do not affect the other.

The copy constructor is an idiomatic way in Java to perform deep copying, especially when control over the copying process is required.

What is a copy constructor? — Java - sobes.tech