Implementing Incompatible Interfaces

I am trying to create 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 //... } 

Erasing a type K causes these two method signatures to collide. I cannot have one of them, because this is an unacceptable redefinition, and I cannot have both, because they have the same signature. Is there a way I can combine these two interfaces?

+7
source share
2 answers

I do not think this is possible in this particular case. If both classes return object types, you will have some chance, but since you are mixing base and object types, there is no compatible type that supports both interfaces.

Another approach may be to implement appropriate interfaces that are compatible, and then use composition to preserve the internal structure and calls of the map function, if necessary. This assumes that you do not need to be satisfied or suitable for use as both interfaces, but rather that you need to expose.

However, if you need to make this class interchangeable as two incompatible interfaces, this cannot be done.

+4
source

You can create your own MyQueue interface with all the methods in which Queue has a minus delete method, and use it. You can provide the MyQueue a Queue toQueue() interface, which returns an object converted to a queue.

This conversion process may simply involve returning a new instance of anonymous Queue , which for each method X will simply call / return this. [X]. For the delete method, you call this.remove() , but then return a boolean, rather than return value, of the call to this.remove() .

0
source

All Articles