Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conflicting interface methods in Java [duplicate]

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?

like image 410
arshajii Avatar asked Oct 08 '12 13:10

arshajii


2 Answers

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();
like image 169
Peter Lawrey Avatar answered Oct 17 '22 05:10

Peter Lawrey


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

like image 28
Samuel Avatar answered Oct 17 '22 04:10

Samuel