Java - Method Name Collision in Interface Implementation

Java - Method name collision in interface implementation

No, there is no way to implement the same method in two different ways in one class in Java.

That can lead to many confusing situations, which is why Java has disallowed it.

interface ISomething {
void doSomething();
}

interface ISomething2 {
void doSomething();
}

class Impl implements ISomething, ISomething2 {
void doSomething() {} // There can only be one implementation of this method.
}

What you can do is compose a class out of two classes that each implement a different interface. Then that one class will have the behavior of both interfaces.

class CompositeClass {
ISomething class1;
ISomething2 class2;
void doSomething1(){class1.doSomething();}
void doSomething2(){class2.doSomething();}
}

How to solve name conflict of method in two interfaces

You can't implement both interfaces unless the methods differ in parameter types (or method name) when they return different types.

From JLS-8.1.5,

a class cannot have multiple methods with the same signature and different primitive return types (§8.4).

Conflicting interface methods in Java

The simplest solution is to always return double in A as it can store every possible int value.

If you is not an option you need to use an alternative to inheritance.

class C {
public A getA();
public B getB();
}

C c = new C();
int a = c.getA().foo();
double b = c.getB().foo();

How to implement contradictory interfaces

Short answer: you can't.

What you can do is provide a view that implements one or the other interface. For instance:

public class OnePossibleSolution { // no "implements"

private String interface1Method() {
return "whatever";
}

public Interface1 asInterface1() {
return new Interface1() {
@Override
String method() {
return interface1Method();
}
}
}

// ditto for Interface2...

This is probably the most Java-idiomatic way to solve the problem. It's what Map does when you want to iterate over its elements, for instance. Rather than try to solve the problem of being an Iterable<K>, Iterable<V> and Iterable<Map.Entry<K,V>>, it provides three views:

  • keySet()
  • values()
  • entrySet()

Each of those returns a respective collection, which implements the appropriate Iterable<...> interface.



Related Topics



Leave a reply



Submit