![](/img/trans.png)
[英]How to make a Java interface that extends Iterable with two different generic types?
[英]How to interface can extends 2 with that extends the same but with different generic parameters in java?
问题:
基础接口:
IBase
后人:
InterfaceA extends IBase<Interface1>
InterfaceB extends IBase<Interface2>
当我尝试:
InterfaceC extends InterfaceA, InterfaceB
我收到编译错误:
The interface IBase cannot be implemented more than once with different arguments
是否存在解决方法? 谢谢。
这是不可能的,至少它不能用Java。 考虑以下情况:
interface Base<K> {
K get();
}
interface A extends Base<String> {
String get();
}
interface B extends Base<Integer> {
Integer get();
}
interface AB extends A, B {
??
}
当你试图实现AB时,如果可能的话,get()方法将返回什么类型。 在Java中,类中的两个方法不能具有相同的名称/ args但返回类型不同....因此,这是禁止的。
如果你真的需要一些类似于Java所允许的功能,我建议如下:
abstract class C {
A a;
B b;
String aGet() {
return a.get();
}
Integer bGet() {
return b.get();
}
}
或者,保持泛型:
abstract class C<K, T> {
Base<K> a;
Base<T> b;
K getA() {
return a.get();
}
T getB() {
return b.get();
}
}
泛型基本上只是编译时间检查,因此InterfaceA和InterfaceB是相同的。
您建议的一般解决方法很难提出,您可能需要更多地指定您的确切情况。 但是你真的需要THAT类来实现这两个,为什么不是两个不同的类? 也许是嵌套类,甚至是匿名内部类?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.