我有一个基类Thing,它提供了一些基本功能,包括使用Thing子类的类型参数获取对ThingInfo的引用.因为
Java没有自我类型,所以我不能将它用于ThingInfo返回值的类型参数,因此Thing必须采用递归类型参数以允许我们返回正确的参数化ThingInfo.
interface ThingInfo
{
// just an example method showing that ThingInfo needs to know about
// the type parameter T
T getThing();
}
class Thing>
{
// I need to be able to return a ThingInfo with the type parameter
// of the sub class of Thing. ie. ThingA.getThingInfo() must return
// a ThingInfo.
// This is where Java would benefit from self types, as I could declare
// the method something like: ThingInfo getThingInfo()
// and Thing would not need a type parameter.
ThingInfo getThingInfo()
{
return something;
}
}
// example Thing implementation
class ThingA extends Thing
{
}
// example Thing implementation
class ThingB extends Thing
{
}
到目前为止一切都很好.此代码可根据需要运行.
我还需要表示事物之间的类型安全关系.
class ThingRelation, Y extends Thing>
{
X getParent()
{
return something;
}
Y getChild()
{
return something;
}
}
它不是那么简单,但这表明了我的需要.尽管如此,所有这一切都很好,没有错误.现在,ThingRelation需要在Y和其他Thing之间采用ThingRelation参数的方法.所以我将ThingRelation更改为以下内容:
class ThingRelation, Y extends Thing>
{
X getParent()
{
return something;
}
Y getChild()
{
return something;
}
> void useRelation(ThingRelation relation)
{
// do something;
}
}
但是现在我在编译时遇到了这个错误:
type argument Y is not within bounds of type-variable X
where Y,X are type-variables:
Y extends Thing declared in class ThingRelation
X extends Thing declared in class ThingRelation
错误是在行开始< Z extends Thing< Z>> ….
究竟是什么问题呢?
更新:javac版本是1.7.0_05.