微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 从父对象创建子对象的最佳方法[复制]

参见英文答案 > Java: Creating a subclass object from a parent object10个
在给父母提供数据的情况下,创建孩子的最佳方法是哪种?
是否可以在子类上使用包含所有父值的方法
public class Child extends Person {
  public Child(Parent p) {
    this.setParentField1(p.getParentField1());
    this.setParentField2(p.getParentField2());
    this.setParentField3(p.getParentField3());
    // other parent fields.
  }
}

复制父数据ti子对象?

Child child = new Child(p);

解决方法

我建议在父类中创建一个接受Parent类型对象的构造函数.
public class Child extends Parent {
  public Child(Parent p) {
     super(p);
  }
}

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

原文地址:https://www.jb51.cc/java/124745.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐