小编use*_*786的帖子

Java中的多态副本

我突然遇到了在Java中制作深度多态副本的问题.实现Clonable解决了我的问题,但它通常被称为"坏"技术.

所以,我试图找到一个"不可克隆"的解决方案:

public class Parent {
    int x;

    public Parent() {}

    public Parent(int x0) {
        x = x0;
    }

    public Parent copy() {
        Parent b = new Parent();
        b.assign(this);

        return b;
    }

    protected void assign(Parent c) {
        x = c.x;
    }

    @Override
    public String toString() {
        return getClass().getName() + ", " + x;
    }
}

public class Child extends Parent {
    int y;

    protected Child() {}

    public Child(int x0, int y0) {
        super(x0);
        y = y0;
    }

    @Override …
Run Code Online (Sandbox Code Playgroud)

java reflection polymorphism deep-copy

5
推荐指数
1
解决办法
776
查看次数

标签 统计

deep-copy ×1

java ×1

polymorphism ×1

reflection ×1