Reputation: 1231
Java here. I've got the following situation:
abstract class A { /*...*/ };
class Derived1 extends A { /*...*/ };
class Derived2 extends A { /*...*/ };
class Derived3 extends A { /*...*/ };
and elsewhere in the code someone sends me objects of type 'A':
A obj1 = getObject();
now I'd like to do a deep copy of object 'obj1', something like
A obj2 = obj1.deepCopy();
but I don't know how to implement this. I don't know the type of obj1 (well, it is either Derived1, Derived2 or Derived3).
Is it possible to write a deep copy function once and avoid doing things like
if( obj1 instancef Derived1 )
{
A obj2 = new Derived1((Derived1)obj1);
}
and having to implement three copy constructors?
Upvotes: 0
Views: 141
Reputation: 3314
yes by using a polymorphic deepCopy
method.
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
Upvotes: 1