我有三个班级:
Base extends Object
Derived1 extends Base
Derived2 extends Derived1
每个类都有自己的字段,应该克隆。我理解实现clone
的最佳方法并避免重复代码时遇到麻烦。我有以下架构,但对我来说看起来最糟糕
Derived2.clone()
:它调用super.clone()
并收到Derived1
的对象。然后,它会调用新的Derived2(objOfDerived1)
调用super(objOfDerived1)
复制其所有字段,然后在Derived2.clone()
中复制Derived2
的所有字段。
你会怎么说?也许有任何文章描述这个问题?
UPD:这个想法可以在这里显示
class Base implements Cloneable {
private String dataOfBase;
public Base() {
}
public Base(Base base) {
this.dataOfBase = base.dataOfBase;
}
@Override
public Object clone() {
Base base = new Base();
base.dataOfBase = dataOfBase;
return base;
}
}
class Derived extends Base {
private String dataOfDerived;
public Derived(Base base) {
super(base);
}
@Override
public Object clone() {
Base base = super.clone();
Derived derived = new Derived(base);
derived.dataOfDerived = dataOfDerived;
return derived;
}
}
答案 0 :(得分:4)
您可以根据复制构造函数实现clone
:
class Base {
private String dataOfBase;
...
public Base(Base other) {
this.dataOfBase = other.dataOfBase;
}
@Override
public Base clone() { // Covariant return type
return new Base(this); // calling copy constructor
}
}
class Derived extends Base {
private String dataOfDerived;
...
public Derived(Derived other) {
super(other);
this.dataOfDerived = other.dataOfDerived;
}
@Override
public Derived clone() {
return new Derived(this);
}
}
答案 1 :(得分:1)
这样的事情怎么样?它允许您直接克隆层次结构中的任何类,并包含层次结构中更高级别的所有类的数据。
public class Derived1 extends Base {
public Derived1 clone(Derived1 foo) {
super.clone(foo);
// copy fields from Derived1
return foo;
}
public Derived1 clone() {
Derived1 foo = new Derived1();
return this.clone(foo);
}
}