Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Incompatible Interfaces [duplicate]

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

    //...
}

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?

like image 673
gobernador Avatar asked Jun 18 '13 16:06

gobernador


1 Answers

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 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.

like image 101
user1676075 Avatar answered Sep 28 '22 07:09

user1676075