Just for the curiosity I tried this:
public interface test1 {
public Object method1(String str);
}
public interface test2 {
public Object method1(String str);
}
public class Test implements test1, test2 {
public static void main(String... args) {
}
public Object method1(String str) {
return new Object();
}
}
I was expecting some sort of error on line public class Test implements test1, test2 { from Eclipse, but there was none.
- Why there is no compile time error since there is a collision of
method names? - How many methods are inherited in
class Test? - If the answer of the above question is 2, then exactly which method
have we implemented? - And at runtime, how come the properly implemented method is
selected? and not the other one? - And finally, is there a way to implement both? (I am almost sure that the answer is NO)
I know that from the design point of view, this may not happen in the real world situations, but as I have mentioned at the beginning, it just came to my mind and I tried it out.
Any clarification/reference is greatly appreciated.
There is no collision. Both interfaces require a method called
method1, and both are satisfied by themethod1in your example class. When you implement an interface, you are not inheriting any methods at all; you are only promising to implement the methods yourself.For the answer to your final question, see this existing SO question:
Java – Method name collision in interface implementation
There is a proposal for Java 8 to allow interfaces to specify a default implementation, called Virtual Extension Methods. If that makes it into the language, it will be possible for two interfaces to specify different default implementations for the same method signature. If those interfaces are then implemented by one class then it will have to provide its own implementation (i.e. it will be equivalent to neither interface specifying a default) – see 3.3. Conflicting defaults.