问题描述
我正在尝试确定是否应该使用接口
与抽象类的一般规则。使用
一个或另一个有什么设计优势吗?
Brad
I''m trying to determine if there''s a general rule for when an Interface
should used vs. an Abstract Class. Is there any design advantage to using
one or the other?
Brad
推荐答案
似乎一个好的起点是看看
之间的区别
两个。对于初学者来说,实现接口的人可以实现多个接口的
,也可以有一个基类。有了一个抽象的
基础,这是他们可以拥有的唯一基类,尽管他们可以实现其他接口。这意味着
的两个类完全不相关的任何其他方式都可以实现你的
接口。对于一个抽象类,任何继承自你的抽象
类的人都会更加密切相关,因为他们在继承中都有相同的基本类型(你的抽象类)层次结构。
使用抽象类,如果需要,可以在抽象类中提供一些
实现。一个界面不能提供
的实现。
-
Tom Porterfield
Seems a good place to start is by looking at the difference between the
two. For starters someone implementing an interface can implement
multiple interfaces and can also have a base class. With an abstract
base, that is the only base class they can have, although they could
implement other interfaces. What this means is that two classes that
are completely unrelated in any other way could both implement your
interface. With an abstract class, anyone inheriting from your abstract
class would be more closely related in that they would all have a same
base type (your abstract class) in their inheritance hierarchy.
With an abstract class you can, if you want or need, provide some
implementation in the abstract class. An interface can provide no
implementation.
--
Tom Porterfield
这篇关于接口与抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!