11

データを持つ親を指定して子を作成する最良の方法はどれですか? 次のように、子クラスのすべての親の値を持つメソッドを使用しても問題ありませんか。

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

2 に答える 2

18

type のオブジェクトを受け入れる親クラスにコンストラクターを作成することをお勧めしますParent

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

public class Parent {
   public Parent(Parent p){
      //set fields here
   }
}
于 2013-08-19T22:55:07.257 に答える
0

もっと簡単なのは

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

適切なアクセス修飾子が配置されている場合、子オブジェクトは常にその親のフィールドにアクセスできます。

于 2015-03-03T03:21:47.907 に答える