Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create a child object from its parent [duplicate]

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);
like image 955
Molly Avatar asked Aug 19 '13 22:08

Molly


People also ask

Can we create child class object with parent reference?

The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable.


1 Answers

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
   }
}
like image 92
Kevin Bowersox Avatar answered Oct 02 '22 18:10

Kevin Bowersox