Java 从父对象创建子对象的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18324366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:30:48  来源:igfitidea点击:

Best way to create a child object from its parent

javainheritancedowncast

提问by Molly

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?

复制父数据ti 子对象?

Child child = new Child(p);

回答by Kevin Bowersox

I would recommend creating a constructor in the parent class that accepts an object of type Parent.

我建议在接受类型为 的对象的父类中创建一个构造函数Parent

public class Child extends Parent {
  public Child(Parent p) {
     super(p);
  }
}

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

回答by F.O.O

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.

给定适当的访问修饰符,您的子对象始终可以访问其父对象的字段。