【问题标题】:Copy constructor of subclass that has its own variables [duplicate]具有自己的变量的子类的复制构造函数[重复]
【发布时间】:2018-12-01 20:10:34
【问题描述】:

我有一个名为 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));
}

我正在寻找一种在复制构造函数中设置子类变量的方法。我想我可以用它接收的对象来做这件事,因为我在将它设置为超类对象数组之前将对象创建为子类对象。

【问题讨论】:

  • 由于你接受Account类型,你需要检查你得到的对象是否是CDAccount并强制转换,然后在super(cd)之后赋值变量。或者你可以只接受 CDAccount 作为 CDAccount 类中的参数。

标签: java inheritance copy-constructor


【解决方案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 中实现封装的方式:私有变量可以被同一类的其他实例访问。

【讨论】:

  • 使用instanceof并不是一个好的做法,因为OOP的封装原理。 Encapsulation
  • 在阅读本文之前最终编写了自己的解决方案,但我可以确认这是可行的。尽管通过我到达构造函数的方式,不需要 if else 语句。谢谢你的回答。
【解决方案2】:

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

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

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

这适用于 Java JDK v10.1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2011-08-22
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 2011-07-11
    相关资源
    最近更新 更多