Home > Software design >  Instantiate object that inherits from Abstract MyType<T>
Instantiate object that inherits from Abstract MyType<T>

Time:11-17

I want to have a class (MyClass) that has a member called X. X is variable that inherits from an abstract class MyData. MyData has multiple inheritors. T can be any primitive data type (int, double, strings...). How do I declare this data member X inside of a class and how do I properly initialize it when instantiating MyClass ?

I have Tried to use generics but still didn't figure the proper way to do it. As MyData is abstract and has a generic type, I can't really have a factory that given a type, let suppose Int return the concrete type that inherits from MyData, or can I?

    class TestingClass<PrimType> {
    private MyData<PrimType> X //This is not allowed (X inherits from MyData<T> which is abstract) how do I achieve this?;
 
    public TestingClass() {
        X = InnstantiateMyData();

      }
     //What the signature of this should be?
     public MyData<PrimType> InstantiateMyData(){
           var type = typeof(PrimType)
           if(PrimType == int)
             return IntConcreteDataType;//IntConcreteDataType would be a concrete inheritor from MyData<T>
             ...
      }
    }
    

 public abstract class MyData<T>
    {
       //only methods...
     }

CodePudding user response:

Your factory method’s signature is fine, there are two changes you need to make to the body to get it to compile:

 public MyData<PrimType> InstantiateMyData(){
       var type = typeof(PrimType)
       if(type == typeof(int)) //<— comparing Type
         return (MyData<PrimType>)(object) new IntConcreteDataType();//constructing a concrete instance, casting to abstract generic via System.Object
         ...
  }
  • Related