问题
I am implementing the Map<V,K>
and the Collection<V>
interface in one class, but the remove(Object)
method occurs in both interfaces, therfore eclipse shows me some errors. The return types are different, one returns boolean
and the other V
but that doesn't seem to matter.
Is there some way of telling java/eclipse which method is actually being overridden?
EDIT: I have got an interface that all values must implement, it supplies the value with a getKey() method, making it possible to write an add function for the map. But there seems to be no way to let this one class look as a map and a collection at the same time?
回答1:
No, there is no a direct way.
Actually dynamic binding takes into account the signature excluding the returning type so Java compiler cannot accept the two methods for the same class that have same signature but different return types. If two methods have same names and same parameters than they MUST also have same returning type, unfortunately for you.
The only way is to split the behavior in two different classes and composing them. Maybe a method like Collection<V> asCollection()
or something like that.
回答2:
The Map
already has keySet()
which is collection of keys. Why do you need the Collection also? If it's so, just do two methods like asMap
and asCollecton
which do return different types.
回答3:
No, there isn't a way to resolve such conflicts.
You should consider to use composition and delegation instead of inheritance for at least one of the two interfaces, or you could split the functionality of your class in two classes, it really depends on your concrete problem.
回答4:
You probably need composition instead of inheritance. Unfortunately Java has no language-level support for that - I mean it can be done but it is unnecessarily laborious.
回答5:
You need to rethink your design. Fundamentally, a map is different to a collection. Think about the Collection.add() method. Does it make any sense to add an object without a key or a key without a value to a map?
Your best bet (I think and depending on your application) is to implement a map but when you need a collection, use one of its methods to get the set of keys, values or key value pairs.
来源:https://stackoverflow.com/questions/7818998/java-overriding-two-interfaces-clash-of-method-names