Conflicting interface methods in Java [duplicate]

只愿长相守 提交于 2019-11-30 00:44:57

问题


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?


回答1:


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();



回答2:


You cant. Java uniquely identifies methods by their name and their parameters, not their return type.




回答3:


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(){...}
}



回答4:


Use Number instead of double and int in interface A and B.




回答5:


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.




回答6:


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

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