我写了一些带有继承的泛型,但不能让它工作类型安全。我的目标是提供一个BaseService
关于我可以执行该action(base)
方法的一般信息,无论base
对象是 aFoo 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();
}