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

Copy constructor of subclass that has its own variables

我有一个名为 CDAccount 的子class,它有自己的变量,这些变量没有在超级 class 中定义。

private Calendar maturityDate;
private int termOfCD;

subclass 也有一个复制构造函数接收 superclass 对象。

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

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

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

我正在寻找一种在复制构造函数中设置子class 变量的方法。我认为我可以用它接收的对象来完成它,因为我在将对象设置为 superclass 对象数组之前将其创建为 subclass 对象。

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

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

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

这适用于 Java JDK v10.1

铸造应该为您解决问题:

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 中实现封装的方式:私有变量可以被相同 class 的其他实例访问。