Java是否有默认的拷贝构造函数(比如在C++中)?

the*_*oon 8 c++ java language-comparisons copy-constructor object-construction

Java是否具有C++的默认复制构造函数?如果它有一个 - 如果我明确地声明另一个构造函数(不是复制构造函数),它是否仍然可用?

And*_*san 8

Java没有bulit-in复制构造函数.

但是你可以编写自己的构造函数.请参阅以下示例:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @RomanVottner要扩展,这并不总是很简单,特别是如果你不能改变其中一个可变的字段来给它一个复制构造函数. (2认同)