从抽象类返回子类



假设我有一个基类"Color",有一个sunclass"Primary",还有两个"Blue"one_answers"Red">

颜色要求:

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

所以每种颜色都会覆盖它。但我想覆盖Primary中的功能,这样主体总是一样的:

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(
//...
);
}
}

在这种情况下,red不会有方法foo,因为它已经在Primary中声明了

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

但是,我想返回实际的原色(比如"红色"(,而不是"原色"我可以构造类型为"的返回对象吗;这个";使用类似的东西?

我找不到返回类类型的方法,但使用泛型类型可能会有所帮助:


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>{
}

在这种情况下,SpecificPrimaryColorOfSuperclassRed的方法foo返回类型SpecificPrimaryColorOfSuperclassRed。因此,您创建的每个类都需要从Color继承,才能成为foo将返回的类型

我认为这是不可能的,原因很简单,Primary不知道其子类的构造函数是什么样子的。它们可能没有公共构造函数,或者只有带参数的构造函数。

最新更新