The class implements two interfaces. What interface does the method belong to?

There are two interfaces B and C , each of which has the same method public m1()

 class A implements B and C 

If class A must implement the m1() method, will the implemented method have an interface?

+7
java interface
source share
6 answers

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

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

and

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

will work

+7
source share

This is a common problem, so it is important to have clear names for the teaching methods. And a good OOP design that will make the same methods abstract.

This is also the reason why things are divided into classes.

 Animal.eat() Fish extends Animal Fish.eat() Dog extends Animal Dog.eat() 
+3
source share

The interface does not have a 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() overridden, but does it matter if it is from the interface i or j

+2
source share

Since interfaces have no implementation, this does not matter. There is no deadly diamond of death .

+1
source share

You need to add only one public m1 () method. This will be for both purposes. And if both interfaces have the same parameters, the method declaration will be publicly available m1 ().

+1
source share

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

eg.

  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 is different, it is not clear what should be called, and this will lead to a compilation error of the type "Return type is incompatible with B.doit ()"

+1
source share

All Articles