Java在这里。我有以下情况:
abstract class A { /*...*/ };
class Derived1 extends A { /*...*/ };
class Derived2 extends A { /*...*/ };
class Derived3 extends A { /*...*/ };
在代码的其他地方,有人向我发送了类型为'A'的对象:
A obj1 = getObject();
现在我想复制对象'obj1'的深层副本,例如
A obj2 = obj1.deepCopy();
但是我不知道如何实现。我不知道obj1的类型(好吧,它是Derived1,Derived2或Derived3)。
是否可以只编写一次深层复制函数并避免做类似的事情
if( obj1 instancef Derived1 )
{
A obj2 = new Derived1((Derived1)obj1);
}
并且必须实现三个副本构造函数?
答案 0 :(得分:1)
通过使用多态deepCopy
方法是。
abstract class A {
A(A t) {
}
A() {}
public abstract A deepCopy();
}
class D1 extends A {
D1(D1 t) {
//copy constructor
}
D1() {
//no-arg constructor
}
@Override
public D1 deepCopy() {
return new D1(this);
}
}
A a = new D1();
A copy = a.deepCopy(); //the deepCopy is called D1 class