Two interfaces with same method names and signatures. But implemented by a single class then how the compiler will identify the which method is for which interface?
Ex:
interface A{
int f();
}
interface B{
int f();
}
class Test implements A, B{
public static void main(String... args) throws Exception{
}
@Override
public int f() { // from which interface A or B
return 0;
}
}
If a type implements two interfaces, and each
interfacedefine a method that has identical signature, then in effect there is only one method, and they are not distinguishable. If, say, the two methods have conflicting return types, then it will be a compilation error. This is the general rule of inheritance, method overriding, hiding, and declarations, and applies also to possible conflicts not only between 2 inheritedinterfacemethods, but also aninterfaceand a superclassmethod, or even just conflicts due to type erasure of generics.Compatibility example
Here’s an example where you have an
interface Gift, which has apresent()method (as in, presenting gifts), and also aninterface Guest, which also has apresent()method (as in, the guest is present and not absent).Presentable johnnyis both aGiftand aGuest.The above snippet compiles and runs.
Note that there is only one
@Overridenecessary!!!. This is becauseGift.present()andGuest.present()are “@Override-equivalent” (JLS 8.4.2).Thus,
johnnyonly has one implementation ofpresent(), and it doesn’t matter how you treatjohnny, whether as aGiftor as aGuest, there is only one method to invoke.Incompatibility example
Here’s an example where the two inherited methods are NOT
@Override-equivalent:This further reiterates that inheriting members from an
interfacemust obey the general rule of member declarations. Here we haveGiftandGuestdefinepresent()with incompatible return types: onevoidthe otherboolean. For the same reason that you can’t anvoid present()and aboolean present()in one type, this example results in a compilation error.Summary
You can inherit methods that are
@Override-equivalent, subject to the usual requirements of method overriding and hiding. Since they ARE@Override-equivalent, effectively there is only one method to implement, and thus there’s nothing to distinguish/select from.The compiler does not have to identify which method is for which interface, because once they are determined to be
@Override-equivalent, they’re the same method.Resolving potential incompatibilities may be a tricky task, but that’s another issue altogether.
References