I have several subclasses of a class "A", say B, C, and D. I store several of these in a generic
ArrayList<A> stuff;
B, C, and D have absolutely no different data members than A. The only way they differ is by different overridden methods. I would LIKE to be able to copy any instance of class A to another instance of class A (while retaining the true subclass)
Something like:
A obj1 = (A)new B(...)
A obj2 = (A)new C(...)
A obj3 = obj1.copy();
// (obj3 instanceof B) == true
Normally this would require B, C, and D to implement custom copy methods. However, this seems like a waste since the data members are exactly the same, and they would only exist so that the class is preserved.
Is there any way I could get away with only implementing copy in class A, and still preserving the underlying classes of the objects?
EDIT:
If I'm thinking correctly, the problem I would run into if just the superclass had a copy method:
class A {
int dataMember;
public A copy() {
A ret = new A(); // !!
ret.dataMember = dataMember;
return ret;
}
}
When calling "new" I couldn't generically determine what subclass of A the class is, and furthermore explicitly instantiate an instance of that. Or is there a way to do this?