2012-11-29 132 views
5

经过一番搜索后,我没有找到任何有关复制构造函数和继承问题的良好答案。 我有两个类:用户和受训者。学员继承自用户,并将两个字符串参数添加到学员。 现在我设法创建了User的复制构造函数,但我对Trainee的复制构造函数不满意。 用户拷贝构造函数的代码是这样的:Java复制构造函数和继承

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() 
    ); 
} 

我想在我见习的拷贝构造函数使用超:

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); 

所以我的问题是:是否有更干净的方法来做到这一点?我不能使用超级?

非常感谢您的回答和帮助。

+2

当你使用'超(克隆)什么没有工作' – Xymostech

回答

8

这将是更明智的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...或者可能以其他方式指定它。它可能是可能是是在这种情况下,你真的需要有两个独立的构造函数集 - 一个用于复制构造函数,一个用于“只给我所有的值”构造函数。这实际上取决于你的背景 - 我们无法从中看出。

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

0

我会做:

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()); 
    } 
} 
+0

?我会避免使用'instanceof'运算符,它将您与特定类型联系起来。 –