在 Java 中克隆对象 [3 题] [英] Cloning objects in Java [3 questions]

查看:25
本文介绍了在 Java 中克隆对象 [3 题]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样做会不会调用Asub的clone方法?还是 Asub 深度克隆正确?如果不是,有没有办法通过这种方法获得深度克隆Asub?

will the clone method of Asub be called by doing this? Or is Asub deep cloned properly? If not, is there a way to propery deep clone Asub through this kind of method?

abstract class Top extends TopMost {
    protected Object clone() {
        Object obj = super.clone();
        // deep copy and try catch
    }


}

abstract class A extends Top { 
    protected Object clone() {
        Object obj = super.clone();
       // deep copy and try catch
    } 


}

class Asub extends A {
    protected Object clone() {
        Object obj = super.clone();
        // deep copy and try catch
    }

    public void doSomethingNew() {
    }
}

abstract class TopMost {
    public void someMethod() {
        Top a = (Top) super.clone();
        // more code here
    }
}

public class Main {
    public static void main(String... args) {
        Asub class1 = new Asub();
        class1.someMethod();
    }
}

推荐答案

通过允许所有 abstract 子类实现 super.clone() 基本上什么都不做(因为所有的抽象您示例中的类什么都不做),只是调用(最后)Object.clone() 方法.

By allowing all abstract subclasses implementing super.clone() essentially does nothing (since all your abstract classes in your example are doing nothing) and just call (at the end) Object.clone() method.

我的建议是允许所有具体类(如 ASub)覆盖克隆方法并使用 复制构造函数 习惯用法来创建自身的精确克隆....

My suggestion is to allow all concrete classes (like ASub) to override the clone method and use the copy constructor idiom to create an exact clone of itself....

例如

public abstract class TopMost {

    public TopMost(TopMost rhs) {

    }

}

public abstract class Top extends TopMost {

    public Top(Top rhs) {
        super(rhs);

        //whatever you need from rhs that only is visible from top
    }
}

public abstract class A extends Top { 

    public A (A rhs) {
        super(rhs);

        //TODO: do rhs copy
    }
}

public class ASub extends A {

    public ASub(ASub rhs) {
        super(rhs);

        //TODO: copy other stuff here....
    }

    public Object clone() {
        return new ASub(this);
    }
}

PS 使 TopMost 可复制

这篇关于在 Java 中克隆对象 [3 题]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆