Java overriding two interfaces, clash of method names

不羁的心 提交于 2019-12-05 05:32:49

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.

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.

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!