7

There are two interfaces B and C each having the same method public m1()

class A implements B and C 

If class A has to implement method m1(), the implemented method would be of which interface?

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Anirudh
  • 2,286
  • 4
  • 38
  • 64

6 Answers6

7

I think we can say that A.m1 implements both B.m1 and C.m1. Because both

B b = new A();
b.m1();

and

C c = new A();
c.m1();

will work

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
3

This is a common problem, this is why having clear instructional method names is important. And good OOP design that will make same methods be abstract.

It is also the reason things are separated out in to classes.

Animal.eat()

Fish extends Animal
    Fish.eat()
Dog extends Animal
    Dog.eat()
Peter_James
  • 647
  • 4
  • 14
  • 1
    How does that deal with the question of one method defined in two interfaces? – arne.b Nov 18 '13 at 10:26
  • @arne.b It shows that in good designs and throughout design structure, this cross of method names will be minimized. A common example is `getSauce(...)` and `setSauce(...)` without the get/set it would just be `sauce(...)` which could mean either, or or both. – Peter_James Nov 18 '13 at 10:29
2

Interface have does not have method body,So it hardly matters which method is implemented

See the following example

package test;
public class a implements i,j{

    @Override
    public void run() {
        // TODO Auto-generated method stub

    }

}
package test;

public interface i {
public void run();
}
package test;

public interface j {
public void run();
}

In the class a run() is overridden but does it matter if it is from interface i or j

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
1

Since interfaces do not have the implementation, it doesn't matter. There are no deadly diamond of death sort of issues here.

Kashif Nazar
  • 20,775
  • 5
  • 29
  • 46
1

You have to add only one public m1() method. It will be for both the intefaces. And if both the interfaces have the same parameters,the method declaration will be public m1().

Utsav T
  • 1,515
  • 2
  • 24
  • 42
1

There will be no problem as long as declarations of m1 in B and C are "compatible", i.e. have the same return value.

E.g.

    public interface B {
    void doit();
}

public interface C {
    void doit();
}

public class A implements B, C {

    @Override
    public void doit() {
        // TODO Auto-generated method stub

    }
}

but if the return type differ then it's not clear which is to be called and that will result in compile error like "The return type is incompatible with B.doit()"

user2660000
  • 332
  • 2
  • 3