我写了一些带有继承的泛型,但无法使其工作类型安全。我的目标是提供一个通用的 BaseService
,无论 base
对象是 Foo extends Base
或 Bar extends Base
。
下面的不起作用,为什么?
class Base;
class Foo extends Base;
interface BaseService<T extends Base> {
void action(T base);
}
class FooService implements BaseService<Foo> {
void action(Foo foo) {
}
}
//usage:
//complains that the method is not applicable for the argument,
//and that I should change action(T) to action(Base). Why?
Base base;
getService().action(base);
//just to demonstrate the problem
BaseService<? extends Base> getService() {
return new FooService();
}
最佳答案
泛型的存在是为了进行静态类型检查。写的时候
My goal is to provide a general BaseService on that I can exection the action(base) method, no matter if the base object is a Foo extends Base or Bar extends Base.
您表明您不需要任何静态类型检查。所以要做到这一点,参数类型应该是 Base
而不是 T
.
作为getService()
的返回类型是BaseService<? extends Base>
, 编译器甚至不知道 T
是什么是(除了它是 Base
的一些未知子类型)所以你不能调用 action
方法。但是即使getService()
的返回类型将是 FooService
, 参数类型 T
将是 Foo
, 所以你不能用 Base
类型调用它.
您可能应该多考虑一下您实际上希望编译器通过使用泛型来检查什么。
关于java - 如何在继承中使用泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15736601/