Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating an instance of derived class through the base class without hardcoding
    primarykey
    data
    text
    <p>My problem is as follows:</p> <p>I have a base class that needs to be abstract. It has several derived classes, each with their own special properties that are contained in the Properties member.</p> <p>I need to be able to create a new instance of one of these derived classes, so that all the members are equivalent but modifying the new instance doesn't modify the original.</p> <p>Finally, I want to do it without having to hardcode in every derived type of the base class. (Which would, admittedly, be the easiest solution, however that isn't the point)</p> <p>All the derived classes satisfy an "is-a" relationship to the base class.</p> <p>Here is the code:</p> <pre><code>public abstract class BaseClass { //Default properties here int x, y, z, ...; //Custom made class to hold custom properties protected Attributes Properties; public BaseClass createNewInstance() { return createNewInstanceStep1(); } //Each derived class implements their own version of this, //to handle copying any custom members contained in Properties. protected abstract BaseClass createNewInstanceStep2(); protected BaseClass createNewInstanceStep1() { BaseClass newInstance = new BaseClass(); // &lt;- Doesn't work because class is abstract //Copy default properties newInstance.x = x; newInstance.y = y; newInstance.z = z; //Call the new instance's step 2 method, and return the result. return newInstance.createNewInstanceStep2(); } } </code></pre> <p>The issue with this code is the BaseClass newKeyFrame = new BaseClass(); line. As the class is abstract, you cannot create an instance of it.</p> <p>The problem is that I need to be able to call the constructor of whatever type the derived class is, as they all have different code in their constructors that cannot be shared.</p> <p>I've heard that using Reflection might be a viable solution, however I have no idea how.</p> <p>How can I solve this without having to hardcode in a case for every derived type?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload