Java Interfaces – Implementing Methods with the Same Signature

inheritancejava

I recently found out that I can have two interfaces, one containing a method with the same signature as a method in the other interface. And I can have an interface or class that implements both of afore-mentioned interfaces. So the descendant class/interface implicitly implements two different methods as one method.

Why is this allowed in Java?

I can see numerous problems arising from this. Eclipse, for example, can only find out about implementations for one interface method, but for the second one it doesn't show any implementations at all. Also, I believe that there would be problems with automatic refactoring, like when you want to change the signature of the method in one of the interfaces and the IDE will be unable to correctly change that signature in all implementations (since they implement two different interfaces, and the IDE cannot tell which interface method the implementation is referring to.)

Why don't just make a compiler error like 'interfaces method names clashes' or something like that?

Best Answer

There is no reason why this should be forbidden. The only point of an interface is to ensure that a method with particular signature exists in each implementing class. This is satisfied by any implementing class even if the condition is posed twice.

Granted, when you write an interface you presumably expect a certain meaning for the action of invoking the method, and presumably you document it above the declaration in the interface, but that is not the concern of the compiler. It cannot check whether the implementing class does the right thing, only whether it copies the signature exactly. Asking "Why doesn't the compiler forbid one method to satisfy two interface declarations?" boils down to "why doesn't the compiler prevent me from implementing the wrong semantics when I implement an interface?", and the answer to that question is much easier to see: because it can't! (If the compiler were able to judge your method implementation and forbid it if it contained a bug, then we wouldn't need programmers in the first place, we'd need only the specifications and the compiler.)

Obviously we would like it if implementing an interface guaranteed that the implementing class does the right thing, but that's not something that interfaces can do for you. In fact, I'd argue that it would be a bad thing to add a feature to the compiler that might give the impression that it is!