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?
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?
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
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()
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
Since interfaces do not have the implementation, it doesn't matter. There are no deadly diamond of death sort of issues here.
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().
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()"