简体   繁体   English

使用父类对象创建子类对象?

[英]Using a parent-class Object to create a subclass Object?

I want to create an instance of a subclass that contains all the same fields as the parent Object, just with an extra field or two. 我想创建一个子类的实例,该子类包含与父对象相同的所有字段,只是一个或多个额外字段。 My plan is this: 我的计划是这样的:

public subclass(parentClass parent, String extraField)
{
    super(parent.getField1(), parent.getField2());
    this.extraField = extraField;
}

Is there anything wrong with this design? 这个设计有什么问题吗?

That's fine, it's just a copy-constructor-plus. 很好,这只是一个复制构造函数加。

But ideally, define a copy-constructor on the parent class and use it instead: 但理想情况下,请在父类上定义一个复制构造函数,并改为使用它:

public Subclass(ParentClass parent, String extraField) {
    super(parent); // <=== Using the copy constructor
    this.extraField = extraField;
}

(Also, ideally, use Java standard naming conventions, at least when posting code for others to read... ;-) ) (此外,理想情况下,至少在发布代码供他人阅读时使用Java标准命名约定... ;-))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM