【发布时间】:2011-01-04 21:36:12
【问题描述】:
编辑:我错过了这里的另一个皱纹,结果证明有很大的不同。 doAnotherThing 的方法签名改为:
<T extends Bar> T doAnotherThing(List<Foo<T>> foo) {
return foo.get(0).doSomething();
}
忽略它是List 的事实,只需注意List 是通用类/接口这一事实。我这样调用方法:
doAnotherThing(new ArrayList<FooImpl>);
所以,我有一个这样定义的类和接口:
abstract class Bar {
// some neat stuff
}
class BarImpl extends Bar {
// some cool stuff
}
interface Foo<T extends Bar> {
T doSomething();
}
class FooImpl implements Foo<BarImpl> {
BarImpl doSomething() {
// Does something awesome
}
}
这一切都很好,花花公子,效果很好。
现在,我有这样的方法:
<T extends Bar> T doAnotherThing(List<Foo<T>> foo) {
return foo.get(0).doSomething();
}
此方法是完全不同类中的泛型方法,不属于上述链。
但是,当我尝试以下列方式使用此方法时,我收到一条错误消息,指出类型不匹配:
doAnotherThing(new FooImpl());
FooImpl 实现了Foo<T>,所以我看不出这是一个错误?也许我误解了什么?谢谢
【问题讨论】:
-
在您的示例中,BarImpl 不扩展 Bar。
-
它对我有用。除了你忘了
BarImpl extends Bar -
你能分享一下编译器错误信息吗?
-
类型***中的方法doAnotherThing(Foo
)不适用于参数(FooImpl) -
也许更好地解释文件结构和方法 doAnotherThing 的位置会有所帮助,因为我能够毫无困难地复制。 Bar.java: 抽象类 Bar{ public Bar(){ doAnotherThing(new FooImpl()); }
T doAnotherThing(Foo foo){ return foo.doSomething(); } static class BarImpl extends Bar{} interface Foo { T doSomething(); } 静态类 FooImpl 实现 Foo { public BarImpl doSomething(){ return null; } } }
标签: java generics inheritance types