In the following two interfaces, methodA() identically defined in terms of parameters (none) and return type (int). The implementation class below defines one method with this exact signature. Since this corresponds to both interfaces, you have no problem - any calls made through a link such as InterfaceA or InterfaceB will be sent to this implementation.
The second methodB() is defined as returning any subtype of Number (or Number itself) in InterfaceA . InterfaceB defines methodB() as returning an Integer , which is a subtype of Number . The implementation class actually implements the method with Integer , which corresponds to the contract of both InterfaceA and InterfaceB . There are no problems. The noticed case of methodB() , implemented as returning a Double , however, will not work: although it will satisfy the InterfaceA contract, it will conflict with InterfaceB (which requires Integer ).
If InterfaceA and InterfaceB also indicated (different) contracts for methodC() (commented out in the example), this would be inconsistent and would cause a compiler error. Implementation of both signatures (differing only in return type) is not allowed in Java.
The above rules will also be the case if any parameters were added to the methods. For simplicity, I saved this from an example.
public interface InterfaceA { public int methodA(); public Number methodB(); // public int methodC(); // conflicting return type } public interface InterfaceB { public int methodA(); public Integer methodB(); // public String methodC(); // conflicting return type } public class ImplementationOfAandB implements InterfaceA, InterfaceB { public int methodA() { return 0; } public Integer methodB() { return null; } // This would NOT work: // public Double methodB() { // return null; // } }
Daniel Schneller
source share