Java – the best way to create child objects from parent objects [copy]

See the English answer > java: creating a subclass object from a parent object 10

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

Copy parent data and child objects?

Child child = new Child(p);

Solution

I suggest 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
   }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>