java 泛型 递归类型限制_Java泛型与递归类型参数绑定

我有一个基类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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值