I have an abstract class with several subclasses. In the abstract classe I have implemented a copy constructor. Now, I want to clone one of the subclasses using the copy constructor, how can I do this? Obviously I do not know in advance what subclass I have to clone.
Here is an example of what I want to do :
abstract class AbstractClass {
public AbstractClass(AbstractClass ac) {
this();
setX(ac.getX());
setY(ac.getY());
}
// Some setter and getter for X and Y variables
}
class SubclassA extends AbstractClass {
public SubclassA(SubclassA a) {
super(a);
}
}
class SubclassB extends AbstractClass {
public SubclassB(SubclassB b) {
super(b);
}
}
public class Main {
public static void main(String[] args) {
AbstractClass a = new SubclassA();
AbstractClass b = new SubclassB();
// Get a copy of "a" or "b" using the copy constructor of abstract class
AbstractClass newA = AbstractClass(a);
AbstractClass newB = AbstractClass(b);
}
}