Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 953
thedarkside ofthemoon Avatar asked Dec 09 '13 13:12

thedarkside ofthemoon


4 Answers

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
    }
}
like image 198
Andrei Nicusan Avatar answered Sep 20 '22 23:09

Andrei Nicusan


Java does not have a default copy constructor. You'll need to define it yourself.

like image 28
Simeon Visser Avatar answered Sep 21 '22 23:09

Simeon Visser


There is a copy constructor (But not default one), but it should be called explicitly (In C++ it'll be implicitly called when needed):

public MyClass(MyClass toCopy) { 
   someField = toCopy.someField; 
}
like image 36
Maroun Avatar answered Sep 20 '22 23:09

Maroun


No, it doesn't have a default copy constructor. A default constructor.

You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.

Usually I provide a one like,

public class CopyConEx {

      /**
      * Regular constructor.
      */
      public CopyConEx(type  field1, type field2) {
        this.field1 = field1;
        this.field2 = field2;
      }

      /**
      * Copy constructor.
      */
      public CopyConEx(CopyConEx aCopyConEx) {
        this(aCopyConEx.getField1(), aCopyConEx.getField2());   

      }
like image 22
Suresh Atta Avatar answered Sep 19 '22 23:09

Suresh Atta