问题
In the following code snippets, first one does not compile, but second one does . Why? What is the difference?
1.
public class test {
static interface I1 { I1 m(); }
static interface I2 { I2 m(); }
static interface I12 extends I1,I2 {
public I12 m();
}
}
2.
public class test {
static interface I1 { I1 m(); }
static interface I2 { I2 m(); }
static class I12 implements I1,I2 {
public I12 m(){
return null;
}
}
}
回答1:
In Java 1.4 or earlier, both snippets should fail to compile. In 1.5 or later, both versions should compile.
If you override a method in Java 1.4, you must provide exactly the same return type as the base class method does.
This restriction was lifted in Java 1.5 and later, here you are allowed to provide a return type that inherits from the base class method's return type.
This makes sense, and can be useful. If you have:
I1 x = new I12Impl();
then all you know is x.m() returns an I1.
But if you have a bit more information:
I12 x = new I12Impl();
then you know that x.m() returns an I12 (which is also an I1).
This can be handy at times (for example, you might be able to avoid a downcast when calling x.m())
回答2:
The class is allowed to implement multiple interfaces, but when interfaces extends multiple interfaces and both the parent interfaces are having same named method, it gives error other than that there is not any problem. That is the only reason it shows no error in IDE becuase IDE(eclipse) has its own compiler and does not use javac for compilation.
来源:https://stackoverflow.com/questions/9714880/java-inherit-2-interfaces-with-the-same-method