实现不兼容的接口 [英] Implementing Incompatible Interfaces

查看:115
本文介绍了实现不兼容的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个实现 Queue Map 的类。两个接口都定义 remove(Object)方法,但具有不同的返回类型:

I am trying to build a class that implements Queue and Map. Both interfaces define the remove(Object) method, but with different return types:

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

    //...
}

K的类型擦除导致这两种方法签名要碰撞。我不能拥有其中一个,因为它是一个无效的覆盖,我不能同时拥有它们,因为它们具有相同的签名。有什么办法可以让这两个接口共存吗?

The type erasure of K is causing these two method signatures to collide. I can't have one of them because it's an invalid override, and I can't have both because they have the same signature. Is there any way that I can make these two interfaces coexist?

推荐答案

我不相信在这种特殊情况下这是可能的。如果两个类都返回了Object类型,那么你有一些机会,但是由于你在混合基本类型和对象类型,所以没有兼容的类型可以支持这两个接口。

I don't believe that's possible in this particular case. If both classes returned Object types you'd have some chance, but since you're mixing basic and object types, there's no compatible type that would support both interfaces.

A不同的方法可能是实现兼容的适当接口,然后使用组合来存储内部结构并根据需要映射函数调用。这将假设您不需要满足或可用作两个接口,而是特别是您需要公开的接口。

A different approach may be to implement appropriate interfaces that are compatible, then use composition to store an internal structure and map function calls to that as needed. That would assume that you don't need to satisfy or be usable as both interfaces, but rather that one in particular is the one you need to expose.

但是,如果你需要将这个类替换成两个不兼容的接口,不能这样做。

However, if you need to make this class replaceable as two incompatible interfaces, it can't be done.

这篇关于实现不兼容的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆