Overriding return type in extended interface - Bad idea?

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

    No, that's fine. Since ICoolEngine extends IEngine, any object implementing ICoolEngine can be treated as if it's an IEngine (without all the ICoolEngine-specific methods of course). You'll just have to be aware of the type difference depending on which interface you are working with in each situation, and make sure not to use ICoolEngine methods that aren't defined in IEngine (assuming that, in your actual code, there are additional methods listed in the equivalent of ICoolEngine).

    It's not a bad practice to do this; you're simply using the power of polymorphism.

提交回复
热议问题