Suppose I have two interfaces:
interface IOne {
public void method();
}
and
interface ITwo {
public void method();
}
A concrete class implements both of the interfaces:
public class A implements IOne, ITwo {
public void method(){
//some implementation
}
}
My questions are:
- Does the single implementation of
method()
suffice for both interfaces IOne and ITwo? - If the answer of 1 is yes, is there any way to get both the methods in a single class? In this case it is not necessary we have to implement both interfaces in a single class.
For 1, the answer is yes. It's enough to provide one implementation for the method in the class for both interfaces to be automatically implemented.
For 2, if you need to have both methods, then your class should not implement both interfaces. However, there's a trick you can use:
Testing code:
Class
A
doesn't need to implement both interfaces. In that case, just don't implementmethod()
onA
and keep only the anonymous inner classes.If both methods have the same signature, as it is the case in your example, only one implementation is possible. In this case, there is no way to implement two versions of the method for the two interfaces. So yes, the example will suffice.
If the signature is the same for the two methods, but they have different return types, this will result in a compilation error.
If the two methods have different signatures, there can and have to be two different implementations.
Yes. That one method will be called when the class is accessed as an instance of
IOne
, orITwo
.No. A method's name, return type, and arguments define a method's signature, and two methods within the same class cannot have the same signature. Doing so results in a compile time error.
One solution I suggest is to use different method names for IOne.method and ITwo.method, thereby making each method's signature unique. This would allow you to define two unique methods in a single class.
Yes. The implementation is the same for both
abstract
methods.No.