11

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);
Molly
  • 297
  • 1
  • 5
  • 16

2 Answers2

18

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
   }
}
user1766169
  • 1,842
  • 3
  • 22
  • 42
Kevin Bowersox
  • 90,944
  • 18
  • 150
  • 184
0

Much simpler is

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

Your child object always has access to its parent's fields given the appropriate access modifiers are in place.

user1766169
  • 1,842
  • 3
  • 22
  • 42
F.O.O
  • 4,354
  • 4
  • 21
  • 32