0

I'm studying for the 1Z0-819 exam and learned that a class cannot implement two interfaces having the same signature (method name + param type list) but different return types. I know there are several other questions on SO asking if you can do this, or asking about ways around it... I'm wondering why the writers of Java haven't built in a way to accomplish this. I imagine this is a real practical problem for library distributors - I would think trying to ensure a new package is compatible with the largest possible number of other libraries would be extremely difficult... Is this a conversation amongst library distributors?

John Fisher
  • 305
  • 1
  • 13
  • It seems to be possible at the JVM level, not at the level of the language: https://stackoverflow.com/questions/6827363/bytecode-features-not-available-in-the-java-language . See also: https://softwareengineering.stackexchange.com/questions/317082/why-isnt-the-overloading-with-return-types-allowed-at-least-in-usually-used-l . How would you resolve such a call at the call site if you could add such a feature to Java? – terrorrussia-keeps-killing Dec 14 '20 at 23:40
  • @fluffy, you would definitely need to modify the compilation process but I imagine there are lots of ways to do it. Something like `public int myImplMethod(int a) implementing InterfaceA { return a; } public void myImplMethod(int a) implementing InterfaceB { system.out.printLine(a); }` and then you could call the methods with something like `int response = InterfaceA:myImplMethod(5); InterfaceB:myImplMethod(5);` – John Fisher Dec 15 '20 at 01:12
  • Explicit interface implementation, with syntax very similar to what you suggested, is supported in C#: https://stackoverflow.com/questions/143405/c-sharp-interfaces-implicit-implementation-versus-explicit-implementation . Now suppose your library exposes single interface method `int eval()`, and your library consumer uses it, the only one (e.g. `Number n = o.eval();`). After a while you decide to add another explicit interface method to your library, say `float eval()`, but the consumer code remains not-recompiled for whatever reason, so it's ambiguous. What would JVM do then? – terrorrussia-keeps-killing Dec 15 '20 at 08:16
  • @fluffy, without recompiling, the jvm wouldn't have the updated version of the interface, right? – John Fisher Dec 15 '20 at 18:59

0 Answers0