Scenario: I have a hierarchy of subclasses all inheriting from a single distance ancestral class. All super classes in the hierarchy are abstract, so the only concrete classes are those without subclasses. I have an array:
AncestralClass[] someObjects1 = new AncestralClass[someLength];
The ancestralClass is the single super class at the top of the hierarchy that all other classes inherit from. This array is populated with different objects of the various concrete subclasses. For example:
someObjects1[4] = new SubclassObject();
... and so on.
I have a second array of the same exact form (same type, size, etc), but the second array uses the first array to populate itself with objects again belonging to the various concrete subclasses. To be more specific, the object type in an element in the second array, will be decided based on the object type found in the same element of the first array. So the problem I have is this: I won't know what is contained in the first array because its contents are generated randomly at runtime, therefore I will not know what the contents of the second array should be as they are dependent on the first array. I am not sure how to write the code that instantiates the new objects in the second array. Written in English, what I want to happen sounds so simple and easy. I want to loop through the second array, check the corresponding position in the first array, check what kind of object that is, and then instantiate a new object of that type in the second array. That right there is what I don't know how to code:
someObjects2[i] = new (subclass that someObjects1[i] belongs to)();
Question To be more general, I want to instantiate a new object that is a new instance of a class an existing object belongs to. How do I do this, and I'm sure there's multiple solutions, so which is better?