【发布时间】:2011-01-20 12:48:43
【问题描述】:
是否可以指定返回实现两个或多个接口的对象的方法?
假设我们有以下接口:
interface FooBar {
[Foo] & [Bar] getFooBar();
}
interface Foo {
void doFoo();
}
inteface Bar {
void doBar();
}
FooBar 的实现者需要提供getFooBar() 方法,该方法返回一个类型的实例,该类型满足Foo 和Bar。
到目前为止,我尝试的是使用泛型:
interface FooBar {
<T extends Foo & Bar> T getFooBar()
}
class SomeImplementor implements FooBar {
private FooAndBarImpl fSomeField;
public <T extends Foo & Bar> T getFooBar() {
return fSomeField;
}
}
鉴于FooAndBarImpl 是框架或库提供的某种类型,并实现了Foo 和Bar,我认为这应该可以工作。但是,它没有,因为“FooAndBarImpl 无法转换为 T”。这是为什么? getFooBar() 所暗示的合同在我看来并没有被破坏。
另一种解决方案是定义一个扩展Foo 和Bar 的新接口并将其用作返回类型。我只是认为在getFooBar() 实现中为fSomeField 返回一个空包装器没有多大意义。
编辑:
如果有人能解释为什么泛型方法不起作用,将不胜感激。我只是没看到。
【问题讨论】:
-
在你更新后更新了我的答案,包括(我认为)对泛型问题的一个很好的解释
标签: java generics inheritance interface return-value