Best way to create a child object from its parent

Molly picture Molly · Aug 20, 2013 · Viewed 14.3k times · Source

Which is the best way to create a child given a parent with data? Would it be ok to have a method with all parents values on the child class as:

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

to copy parent data ti child object?

Child child = new Child(p);

Answer

Kevin Bowersox picture Kevin Bowersox · Aug 20, 2013

I would recommend creating a constructor in the parent class that accepts an object of type Parent.

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

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