Copy constructor

For self-defined classes, it may not make sense in some cases to simply copy the contents of the class. The programmer of a class can therefore tell the compiler which code to use for copying. This is done by defining the so-called copy constructor, i.e. a constructor that receives a constant reference of the same class as an argument.

Such a constructor takes an object of its own class as a parameter and initializes itself based on the passed object. A copy constructor is applied to uninitialized objects. It assigns a copy of the source object to an uninitialized target object. The copy constructor is an alternative to the clone() method in Java.

Syntax

public class ClassName {
    ClassName() {

    }

    ClassName(ClassName obj) {
    }

    public static void main(String[] args) {
        ClassName obj1 = new ClassName();
        ClassName obj2 = new ClassName(obj1);
    }
}

Example 1

public class Person {
    String name;

    Person() {

    }

    Person(Person person) {
        this.name = person.name;
        System.out.print("Hello " + name);
    }

    public static void main(String[] args) {
        Person p1 = new Person();
        p1.name = "Michael";
        Person p2 = new Person(p1);
    }
}
Output
Hello Michael

Example 2

public class Cube {
    int length, width, height;

    Cube () {

    }

    Cube(Cube cube) {
        this.length = cube.length;
        this.width = cube.width;
        this.height = cube.height;
    }

    int getVolume() {
        return length * width * height;
    }

    public static void main(String[] args) {
        Cube c1 = new Cube();
        c1.length = 2;
        c1.width = 3;
        c1.height = 4;

        Cube c2 = new Cube(c1);
    
        System.out.print(c2.getVolume());
    }
}
Output
24