java - 在Java中,我可以将子类 "based on"的实例作为父类(super class)的实例吗?

标签 java inheritance

假设我有一个类Child,它扩展了另一个类Parent:

public class Parent {
    private String value;
    public Parent() { }
    public String getValue() { return this.value; }
    public void setValue(String value) { this.value = value; }
}

public class Child extends Parent {
    private String anotherValue;
    public Child() { super(); }
    public String getAnotherValue() { return this.anotherValue; }
    public void setAnotherValue() { this.anotherValue = anotherValue; }
}

现在,对于 Parent 类的任何实例 parent 并希望构造 Child 类的实例 child > 这样对象 child 就扩展了对象 parent,即在本例中为 child.getValue().equals(parent.getValue()).

实现此目的的一种方法是向 Child 添加构造函数,如下所示:

    public Child(Parent parent) {
        this.setValue(parent.getValue());
    }

这可以完成工作,但如果父类(super class)更复杂,则可能会很挑剔,而且更重要的是,随着父类(super class)随着时间的推移而发展,这个构造函数应该不断更新,这可能会被遗忘,或多或少会产生灾难性的影响。

也可以通过反射来完成,但这可能有点过分了。

所以我想知道是否有任何Java native 方法可以做到这一点:创建子类的实例并复制父类(super class)实例的所有属性。这在某种程度上是相反的类型转换。

最佳答案

不,没有内置支持可以自动执行此操作。当您想要复制字段值时,常见的模式是为 ParentChild 类创建复制构造函数:

public class Parent {
    public int a;
    public String s;

    public Parent(Parent src) {
        this.a = src.a;
        this.s = src.s;
    }

    // +init-constructor
}

public class Child extends Parent {
    public double d;

    public Child(Child src) {
        super(src);
        this.d = src.d;
    }

    // +init-constructor
}

编辑

如果您只想从父类(super class) Parent 复制字段,我会添加另一个仅复制父字段的复制构造函数:

public class Child extends Parent {
    // +fields

    // +copy-constructor Child(Child src)

    public Child(Parent src) {
        super(src);
    }

    // +init-constructor
}

因此,将根据实例的类型选择正确的构造函数。

Parent p = new Parent(1, "a");
Child c = new Child(1, "a", 2.0);

Child pCopy = new Child(p);
Child cCopy = new Child(c);

注意,您还可以显式地将子实例向上转换为父类型,以防您只想从子实例复制父字段:

Child c = new Child(1, "a", 2.0);
Child  pCopy  = new Child((Parent) c);

如果您想将字段复制到已经构造的子级,我会做类似您在 @KarlNicholas 的回答中看到的操作。

关于java - 在Java中,我可以将子类 "based on"的实例作为父类(super class)的实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44807875/

相关文章:

c++ - 为什么虚拟基类必须由最派生的类来构造?

c# - 无法转换类型 : why is it necesssary to cast twice?

java - 创建新线程报错 "constructor test in class test cannot be applied to given types"

java - 在滚动复合中使用 GridLayout

c++ - 为什么我可以通过指向派生对象的基类指针访问派生私有(private)成员函数?

c++ - 如何使用 Base 和 Derived 对象默认初始化 std::vector<Base> ?

c++ - 在类 Base 中实现函数的最有效方法

java - 调用构造函数时数据类型不正确

java - 除非 GPS 开启,否则融合位置提供程序无法获取位置

java - 日期选择器不显示转换后的日期