在继承结构上实现可克隆接口的Java
我的代码中有以下问题:在继承结构上实现可克隆接口的Java,java,inheritance,cloneable,interface-implementation,Java,Inheritance,Cloneable,Interface Implementation,我的代码中有以下问题: public class Parent { ... } public class Child extends Parent implements Cloneable { ... @Override public Child clone() { return new Child() //deep copy } } 以下是我的问题: 遵循java约定;我是否也需要为家长实现Cloneable 我是否必须将抛出Clon
public class Parent {
...
}
public class Child extends Parent implements Cloneable {
...
@Override
public Child clone() {
return new Child() //deep copy
}
}
以下是我的问题:
抛出CloneNotSupportedException
添加到clone()方法中,还是允许我将其放在一旁?因为我无法捕获调用clone()的异常public class Child extends Parent {
public Child(Child child){
this.property = child.getProperty();
// any copies
}
}
Java中的
Cloneable
是,而且通常人们会避免它,而倾向于显式复制构造函数。对于涉及Cloneable
的问题,一般的答案是“不要使用Cloneable
”。我用克隆方法对对象进行了深度复制。到目前为止,深度复制已经实现了这一点。还是说克隆方法不应该这样使用?当你说可克隆是一种遗产时,你的意思是我必须在我的父母身上实现它,才能在我的孩子身上实现它,或者我可以在我的孩子身上实现它。因为我的父母不需要克隆方法,但我的孩子需要克隆方法?不幸的是,我只允许使用Java.util+(regex、stream、function)和Java.lang。不,legacy意味着它已经过时了,应该避免这种情况。如果您已经实现了深度复制,那么最好在构造函数上使用它