缩小继承的返回类型(涉及到的泛型)
问题描述:
我正在琢磨一些关于在子类化时能够“缩小”返回类型的奇怪泛型行为。我设法把问题缩小到以下组类:缩小继承的返回类型(涉及到的泛型)
public class AbstractIndex {
}
public class TreeIndex extends AbstractIndex {
}
public interface IService<T extends AbstractIndex> {
}
public interface ITreeService extends IService<TreeIndex> {
}
public abstract class AbstractServiceTest<T extends AbstractIndex> {
abstract <V extends IService<T>> V getService();
}
public class TreeServiceTest extends AbstractServiceTest<TreeIndex> {
@Override
ITreeService getService() {
return null;
}
}
问题是,当我尝试的getService
返回类型缩小到ITreeService
是Java的警告。该警告是
类型安全:从TreeServiceTest需要选中转换成与类型AbstractServiceTest符合伏类型的getService的返回类型ITreeService()
为什么不ITreeService一个有效的缩小型getService
?
编辑:改变错误警告
答
因为我觉得你的意思是说这个:
public abstract class AbstractServiceTest<T extends AbstractIndex> {
abstract IService<T> getService();
}
没有什么目的,使得单独V
类型的变量,不是添加约束等,你的子类可以”完成。 :-P
+0
谢谢。那样做了。 – JesperE 2010-01-26 16:43:24
答
如果你想拥有AbstractServiceTest
s的不同V
S为同一T
,你可以这样做:
public abstract class AbstractServiceTest<T extends AbstractIndex, V extends IService<T>> {
abstract V getService();
}
public class TreeServiceTest extends AbstractServiceTest<TreeIndex, ITreeService> {
@Override
ITreeService getService() {
return null;
}
}
public class AnotherTreeServiceTest extends AbstractServiceTest<TreeIndex, AnotherTreeService> {
@Override
AnotherTreeService getService() {
return null;
}
}
编辑:但是,它才有意义,如果你还使用V
在其他一些地方,如:
public void setService(V service) { ... }
您的代码编译并运行在这里与Java 6 – jarnbjo 2010-01-26 15:54:25
@jarnbjo,它实际上是一个警告不是错误 – notnoop 2010-01-26 15:55:41
对不起,是的。我的错。这是一个警告,而不是一个错误。我会更新这个问题。 – JesperE 2010-01-26 16:16:25