How do I copy subclasses using the parent abstract copy constructor in Java?

advertisements

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);
    }
}


There are only two ways I can see to create a copy of a given object without knowing at compile time which class to instantiate (as requested in the question):

  1. Use Reflection to call the copy constructor of the desired class, assuming you know at runtime what the class is, and that said class has a suitable copy constructor.
  2. Call some copy method of the base class which is overridden by subclasses.

The first solution is not good as it requires the use of Reflection. The second can be implemented with the clone()/Cloneable standard mechanism (despite its issues), or with some custom-defined "copy()" method. Your choice.