Does Java have a default copy constructor (like in C++)?

thedarkside ofthemoon picture thedarkside ofthemoon · Dec 9, 2013 · Viewed 9.5k times · Source

Does Java has a default copy constructor as C++? If it has one - does it remain usable if I declare another constructor (not a copy constructor) explicitly?

Answer

Andrei Nicusan picture Andrei Nicusan · Dec 9, 2013

Java does not have bulit-in copy constructors.

But you can write your own such constructors. See an example below:

class C{
    private String field;
    private int anotherField;
    private D d;

    public C(){}

    public C(C other){
        this.field = other.field;
        this.anotherField = other.anotherField;
        this.d = new D(other.d); //watch out when copying mutable objects; they should provide copy constructors, as well. Otherwise, a deep copy may not be possible
    }

    //getters and setters
}

class D{//mutable class

    //fields
    public D(D other){
        //this is a copy constructor, like the one for C class
    }
}