2013-08-19 20 views
5

データを持つ親を与えられた子を作成する最良の方法はどれですか?親データTIの子オブジェクトをコピーする親から子オブジェクトを作成する最も良い方法

public class Child extends Person { 
    public Child(Parent p) { 
    this.setParentField1(p.getParentField1()); 
    this.setParentField2(p.getParentField2()); 
    this.setParentField3(p.getParentField3()); 
    // other parent fields. 
    } 
} 

: として子クラス上のすべての親値を持つメソッドを持ってしても大丈夫でしょうか?

Child child = new Child(p); 
+1

人物(){角括弧は不要です。 – initramfs

+0

なぜあなたの '子'は作成される '親'を渡される必要がありますか? –

+0

@tieTYTおそらく多分、彼の恩恵と悪い習慣を含めて正確な子どものクローンがほしいと思うかもしれません。\ –

答えて

9

私はタイプParentのオブジェクトを受け入れ、親クラスのコンストラクタを作成することをお勧めします。

public class Child extends Parent { 
    public Child(Parent p) { 
    super(p); 
    } 
} 

public class Parent { 
    public Parent(Parent p){ 
     //set fields here 
    } 
} 
+0

+1それはスマートです! –

+9

'Person'オブジェクトから' Person'オブジェクトを作成するのはやや意味がありません。 – christopher

+0

それは私が仮定する質問の全体的な点です。 –

0

はるかに簡単にはあなたの子オブジェクトは、常に適切なアクセス修飾子が整備されている与えられた親のフィールドへのアクセスを持っている

 public class Child extends Parent { 
      public Child(Parent p) { 
      //Set fields with parent 
      } 
     } 

です。

関連する問題