A class implements two interfaces. Which interface does a method belong to? [duplicate]

爷,独闯天下 提交于 2020-01-01 09:46:13

问题


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?


回答1:


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




回答2:


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



回答3:


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




回答4:


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




回答5:


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




回答6:


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



来源:https://stackoverflow.com/questions/20045254/a-class-implements-two-interfaces-which-interface-does-a-method-belong-to

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