覆盖扩展接口中的返回类型 - 不好主意? [英] Overriding return type in extended interface - Bad idea?

查看:88
本文介绍了覆盖扩展接口中的返回类型 - 不好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,您可以执行以下操作:

In Java, you can do the following :

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

public interface Car
{
   IEngine getEngine();
}
public interface ICoolCar extends ICar
{
    @Override
    ICoolEngine getEngine();
}

虽然这很好地解决了我一直在努力解决的问题,但有关它的一些问题感觉错了。

While this nicely solves a problem I've been grappling with, something about it "feels" wrong.

我在这里做了一些讨厌的设计失礼吗?

Am I committing some nasty design faux pas here?

推荐答案

不,你做的是正确的事。 Covariant返回只是指定类及其下面的类必须返回父类返回的原始通用类参数的特定子类。这也意味着您的子类仍然需要返回引擎的原始接口兼容,但是如果您知道它是一个ICoolCar,它有一个ICoolEngine - 因为更具体的接口知道更具体的功能。这适用于接口和类 - 这是正确的,适当的和有用的启动。

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.

这篇关于覆盖扩展接口中的返回类型 - 不好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆