Overriding return type in extended interface - Bad idea?

后端 未结 4 1356
天命终不由人
天命终不由人 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 14:55

    No, you are doing the right thing. Covariant returns just specify that the class, and classes below it, must return a specific subclass of the original general class argument that the parent class returned. It also means that your subclasses are still compatible with the original interface that requires that it return an Engine, but if you know that it is an ICoolCar, that it has an ICoolEngine - because the more specific interface knows of more specific functionality. This applies to interfaces as well as classes - this is correct, proper and useful to boot.

提交回复
热议问题