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;
}
}
}
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:
then all you know is x.m() returns an I1.
But if you have a bit more information:
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())