Java有一个默认的复制构造函数(像C ++)? [英] Does Java have a default copy constructor (like in C++)?

查看:641
本文介绍了Java有一个默认的复制构造函数(像C ++)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

Java不有bulit-in复制构造函数。

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
    }
}

这篇关于Java有一个默认的复制构造函数(像C ++)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆