Conflicting interface methods in Java [duplicate]

对着背影说爱祢 提交于 2019-11-30 17:15:16

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.

manub

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.

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