Home > Blockchain >  Return subclass from abstract class
Return subclass from abstract class

Time:03-15

Let's say I have a base class 'Color' with a sunclass 'Primary' and yet another two 'Blue' and 'Red'

Color requires:

abstract class Color {
    Future<Color> foo({required int index});
}

so each color will override it. But I want to override the function in the Primary so the body is always the same:

abstract class Primary extends Color {
    Future<Primary> foo({required int index}) async {
      //In this case, I want the return type to be the same as the object calling it
      return SpecificPrimaryColorOfSubclass(
        //...
      );
    }
}

In this case, red would not have the method foo, because its already declared in Primary

class Red extends Primary {
   //Can call foo and return Red without declaring it
}

However, I would like to return the actual primary color (say 'Red') instead of 'Primary.' Can I construct the returning object with the type of "this" using something like ?

CodePudding user response:

I couldn't find a way to return the class type, but perhaps usage of generic types would help a bit:


abstract class Color<T> {
  Future<T> foo(int index);
}

class Primary<T extends Color> extends Color<T>{
  @override
  Future<T> foo(int index) {
    // TODO: implement foo
    throw UnimplementedError();
  }
}

class SpecificPrimaryColorOfSuperclassRed extends Primary<SpecificPrimaryColorOfSuperclassRed>{

}

In this case, SpecificPrimaryColorOfSuperclassRed's method foo is returning a type SpecificPrimaryColorOfSuperclassRed. So every class you create just needs to inherit from Color to be able to be the type that foo will return

CodePudding user response:

I think it's not possible for the simple reason that Primary can't know what the constructors look like of its subclasses. They might have no public constructors or only constructors with parameters.

  • Related