继承和接口 [英] Inheritance and interfaces

查看:144
本文介绍了继承和接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这对此有一些后续问题问题

This is somewhat of a follow-up question to this question.

假设我有一个继承树,如下所示:

Suppose I have an inheritance tree as follows:

Car -> Ford -> Mustang -> MustangGT

这些类的每个定义接口是否有好处?示例:

Is there a benefit to defining interfaces for each of these classes? Example:

ICar -> IFord -> IMustang -> IMustangGT

我可以看到其他类别(如雪佛兰)想要实现 Icar IFord 甚至可能 IMustang ,但可能不是 IMustangGT 因为它非常具体。在这种情况下接口是多余的吗?

I can see that maybe other classes (like Chevy) would want to implement Icar or IFord and maybe even IMustang, but probably not IMustangGT because it is so specific. Are the interfaces superfluous in this case?

另外,我认为任何想要实现的类 IFord 肯定希望通过继承 Ford 来使用它的一个继承,以免重复代码。如果这是给定的,那么实现 IFord 的好处是什么?

Also, I would think that any class that would want to implement IFord would definitely want to use its one inheritance by inheriting from Ford so as not to duplicate code. If that is a given, what is the benefit of also implementing IFord?

推荐答案

根据我的经验,当你有几个类需要响应相同的方法或方法时,最好使用接口,以便它们可以被其他代码互换使用,这些代码将针对这些类的通用接口进行编写。接口的最佳用途是协议很重要,但每个类的底层逻辑可能不同。如果您原本会复制逻辑,请考虑抽象类或标准类继承。

In my experience, interfaces are best used when you have several classes which each need to respond to the same method or methods so that they can be used interchangeably by other code which will be written against those classes' common interface. The best use of an interface is when the protocol is important but the underlying logic may be different for each class. If you would otherwise be duplicating logic, consider abstract classes or standard class inheritance instead.

为了回答问题的第一部分,我建议不要创建接口为你的每个班级。这会不必要地混乱你的类结构。如果您发现需要界面,可以随时添加。希望这会有所帮助!

And in response to the first part of your question, I would recommend against creating an interface for each of your classes. This would unnecessarily clutter your class structure. If you find you need an interface you can always add it later. Hope this helps!

Adam

这篇关于继承和接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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