2012-11-29 130 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'運算符,它將您與特定類型聯繫起來。 –