抽象类和接口的区别
可能的重复:
接口与基类
我不理解抽象类和接口之间的区别。我什么时候需要使用哪种字体?
Possible Duplicate:
Interface vs Base class
I am not understanding the difference between an abstract class and an interface. When do I need to use which art of type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试这样想:
一个抽象类创建了一个“is-a”关系。大众汽车是汽车。
界面创建了一种“可以做”的关系。 Fred可以 IDrive。
此外,Fred可以 IDrive,但Fred是一个人。
Try thinking of it like this:
An abstract class creates an "is-a" relationship. Volkswagon is a Car.
An interface creates a "can-do" relationship. Fred can IDrive.
Moreover, Fred can IDrive, but Fred is a Person.
当我们创建接口时,我们基本上是在创建一组没有任何必须由已实现的类覆盖的实现的方法。优点是它提供了一种使一个类成为两个类的一部分的方法:一个来自继承层次结构,一个来自接口。
当我们创建抽象类时,我们正在创建一个基类,该基类可能具有一个或多个已完成的方法,但至少有一个或多个方法未完成并声明为抽象。如果抽象类的所有方法都不完整,那么它与接口相同。抽象类的目的是为一组派生类如何工作提供基类定义,然后允许程序员在派生类中填充实现。
文章以及演示项目讨论了接口与抽象类。
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
article along with the demo project discussed Interfaces versus Abstract classes.
抽象类是可能具有一些抽象方法和一些非抽象方法的类。他们做事情(有关联的代码)。如果一个新的非抽象类是抽象类的子类,它必须实现抽象方法。
IE
Interface 更像是一个协议。实现该接口的类必须具有的方法列表。但他们不做任何事情。他们只有方法原型。
两者经常被混淆,因为C++中没有协议/接口。因此,用该语言模拟界面行为的方法是编写一个纯虚类(仅具有纯虚函数的类)。
An abstract class is class probably with some abstract methods and some non-abstract methods. They do stuff (have associated code). If a new non-abstract class, subclasses the abstract class it must implement the abstract methods.
I.E.
Interface is more like a protocol. A list of methods that a class implementing that interface must have. But they don't do anything. They have just method prototypes.
Both are often confused because there is no protocol/interface in C++. So the way to simulate an interface behavior in that language is writing a pure virtual class (a class with only pure virtual functions).