复制具有自己变量的子类的构造函数

时间:2018-12-01 20:10:35

标签: java inheritance copy-constructor

我有一个名为CDAccount的子类,该子类具有其自己的变量,这些变量在超类中未定义。

private Calendar maturityDate;
private int termOfCD;

子类还具有一个复制构造函数,该构造函数接受一个超类对象。

public CDAccount(Account cd){
    super(cd);
}

此构造函数由不同类中的这一行代码调用。

if (accounts.get(index).getType().equals("CD")) {
return new CDAccount(accounts.get(index));
}

我正在寻找一种在复制构造函数中设置子类变量的方法。我认为我可以使用接收的对象来完成此操作,因为在将其设置为超类对象数组之前,我已将该对象创建为子类对象。

2 个答案:

答案 0 :(得分:0)

最佳做法是像这样重载构造函数。

public CDAccount(CDAccount cd){
    super(cd);
    this.maturityDate = cd.getMaturityDate()
    this.termOfCD = cd.getTermOfCD()
}

public CDAccount(Account cd){
    super(cd);
}

这在Java JDK v10.1上对我有效

答案 1 :(得分:0)

铸造应为您解决问题:

public CDAccount(Account cd) {
    super(cd);
    if(cd instanceof CDAccount) {
        this.maturityDate = ((CDAccount)cd).maturityDate;
        this.termOfCD=((CDAccount)cd).termOfCD;
    }
    else {
        this.maturityDate = null;
        this.termOfCD= null;
    }
}

之所以有效,是因为Java中实现了封装的方式:私有变量可供相同类的其他实例访问。