Possible Duplicate:
Method name collision in interface implementation - Java
What do we do if we need to implement two interfaces both of which contain a method with the same name and parameters, but different return types? For example:
interface A {
public int foo();
}
interface B {
public double foo();
}
class C implements A, B {
public int foo() {...} // compilation error
}
Is there an easy way to overcome this issue?
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();
You cant. Java uniquely identifies methods by their name and their parameters, not their return type.
You can write an Adapter class to implement one of the interfaces.
Example implementation:
class AdapterA implements A{
AdapterA(C c){impl = c;}
private final C impl;
public int foo(){return c.fooReturningInt();}
}
class C implements B{
public double foo(){...}
public int fooReturningInt(){...}
}
Use Number instead of double and int in interface A and B.
A method in Java is uniquely defined by its signature. From http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Definition: Two of the components of a method declaration comprise the method signature—the method's name and the parameter types.
Your foo() method is clearly not well defined. Likely there should be a parent interface with a public Number foo(), which is extended by A and B who override that to a more specific type. There isn't really a sensible way your class can implement both those interfaces unless you rename one of the foo methods.
来源:https://stackoverflow.com/questions/12782491/conflicting-interface-methods-in-java