繁体   English   中英

java拷贝构造函数和继承

[英]java copy constructor and inheritance

经过一番搜索,我没有找到关于复制构造函数和继承的问题的任何好答案。 我有两个班:用户和实习生。 学员继承自User,并将两个String参数添加到Trainee。 现在我设法创建了User的复制构造函数,但我对Trainee的复制构造函数不满意。 User copy构造函数的代码如下:

public User (User clone) {
    this(clone.getId(), 
         clone.getCivilite(),
         clone.getNom(), 
         clone.getPrenom(), 
         clone.getEmail(), 
         clone.getLogin(), 
         clone.getTel(), 
         clone.getPortable(), 
         clone.getInscription(), 
         clone.getPw()
    );
}

我试图在我的Trainee拷贝构造函数中使用super:

public Trainee (Trainee clone) {
    super (clone);
    this (clone.getOsia(), clone.getDateNaiss());
}

但它不起作用,我被迫编写完整版本的复制构造函数:

public Trainee (Trainee clone) {
    this(clone.getId(), 
         clone.getCivilite(),
         clone.getNom(),
         clone.getPrenom(), 
         clone.getEmail(), 
         clone.getLogin(), 
         clone.getTel(), 
         clone.getPortable(), 
         clone.getInscription(), 
         clone.getPw(), 
         clone.getOsia(), 
         clone.getDateNaiss()
    );
}

由于我的主要构造我必须像这样投射我的新实例:

  User train = new Trainee();
  User train2 = new Trainee((Trainee) train);

所以我的问题是:有更清洁的方法吗? 我不能用超级?

提前感谢您的回答和帮助。

最好让Trainee的“完整”拷贝构造函数也让User

public Trainee(Trainee clone)
{
    this(clone, clone.getOsai(), clone.getDateNaiss());
}

public Trainee(User clone, String osai, String dateNaiss)
{
    super(clone);
    this.osai = osai;
    this.dateNaiss;
}

尽可能保持每个类中都有一个“主”构造函数的模式,所有其他构造函数都是直接或间接链接的。

现在,尚不清楚在没有指定现有用户信息的情况下创建Trainee是否有意义......或者可能以其他方式指定它。 可能是因为在这种情况下,你真的需要有构造的两套独立的-对拷贝构造函数一组,而对于“只要给我单独所有的值”构造一组。 这实际上取决于你的背景 - 我们不能从中得知。

在这种情况下,您将略微打破“一个主构造函数”规则,但您可以想到有两个主构造函数,每个构造函数用于不同目的。 从根本上说,你正在遇到“继承变得混乱” - 这太常见了:(

我会做:

 public Trainee (User clone) // By specifying `User` you allow the use in your code
 {
    super (clone);
    if (clone instanceof Trainee) {
      this.osia = clone.getOsia();
      this.dateNaiss = clone.getDateNaiss());
    }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM