Overriding return type in extended interface - Bad idea?

后端 未结 4 1349
天命终不由人
天命终不由人 2020-12-16 14:05

In Java, you can do the following :

public interface IEngine{}
public interface ICoolEngine extends IEngine{}

public interface Car
{
   IEngine getEngine();         


        
4条回答
  •  执念已碎
    2020-12-16 15:03

    Covariant return types is a deliberate feature that was added in 1.5 (to support generics primarily).

    @Override may not work for overriding abstract methods with some compilers (javac was updated in 1.6, but the JLS amendment was missed out).

    As always adding an method to an interface risks compatibility issues. Redeclaring a method exactly as in the super-type would be fine, but changing the return type causes a bridge method in implementation classes. This is why Iterable.iterator does not return a read-only version of the Iterator interface.

提交回复
热议问题