gob*_*dor 7 java inheritance interface type-erasure
我正在尝试构建一个实现Queue和的类Map.两个接口都定义了remove(Object)方法,但具有不同的返回类型:
public interface Collection<E> { //Queue extends Collection, which has the problem method
public boolean remove(Object e);
//...
}
public interface Map<K,V> {
public V remove(K key);
//...
}
public class QueuedMap<K,V> extends AbstractMap implements Queue {
public V remove(K key) {/* ... */}
//ERROR: V is not compatible with boolean
//...
}
Run Code Online (Sandbox Code Playgroud)
K的类型擦除导致这两个方法签名发生冲突.我不能拥有其中一个,因为它是一个无效的覆盖,我不能同时拥有它们,因为它们具有相同的签名.有什么办法可以让这两个接口共存吗?
我认为在这种特殊情况下这是不可能的。如果两个类都返回 Object 类型,您就有一些机会,但由于您混合了基本类型和对象类型,因此没有支持这两个接口的兼容类型。
另一种方法可能是实现适当的兼容接口,然后使用组合来存储内部结构并根据需要将函数调用映射到该内部结构。这将假设您不需要满足或可用作这两个接口,而是需要公开一个特定的接口。
但是,如果您需要使此类可替换为两个不兼容的接口,则无法完成。