java - Best way to create a child object from its parent -
this question has answer here:
- java: creating subclass object parent object 11 answers
which best way create child given parent data? ok have method parents values on 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);
i recommend creating constructor in parent class accepts 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 } }
Comments
Post a Comment