接口和抽象类有什么区别?
复制:
可能是最著名的软件开发人员面试问题之一。
你的答案是什么?
编辑:我试图找出您在现实生活中如何回答这个问题。 请尝试像在真正的工作面试中那样制定您的答案(完整,但不要太长,当然不要发布链接)。
Duplicate:
When to use an interface instead of an abstract class and vice versa?
Probably one of the most famous software developer job interview questions.
What would be your answer?
EDIT: I'm trying to find out how you would answer this in a real-life situation. Please try to formulate your answer as you would on a real job interview (be complete, but don't be too long, post no links of course).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
接口仅描述其方法等的实际签名。任何实现该接口的类都必须提供显式实现。
抽象类可以包含其方法等的部分实现。
An interface only describes the actual signature of its methods etc. Any class implementing that interface must then provide an explicit implementation.
An abstract class can contain a partial implementation of its methods etc.
抽象类可以有成员变量,而接口则不能(或者,在 C++ 中,不应该)。
在 Java 中,“接口”是一个定义良好的语法元素,而在 C++ 中,它只是一种设计模式。
An abstract class can have member variables, an interface cannot (or, in C++, should not).
In Java, an "Interface" is a well-defined syntactical element, while in C++ it's merely a design pattern.
接口提供必须由类实现的方法的定义。 接口的目的是让您能够概括特定的功能,而不管实现如何。 您可能有一个具有
Open
/Close
方法的IDatabase
接口。 实现该接口的类可能会连接到 MySQL 数据库或 MS Access 数据库。 无论如何完成此任务,目标仍然是相同的......打开数据库,关闭数据库。抽象类是包含一些抽象方法的基类。 它们不能被实例化,它们是从中派生的。 抽象类的目的是允许您定义一些通用功能和子类,以在适当的情况下实现更具体的功能。
所以总而言之,当每个类的实现完全不同时,您应该使用接口。 当您有一些类似的行为但需要以不同的方式实现某些部分时,请使用抽象类。
希望有帮助。
Interfaces provide definitions of methods that must be implemented by a class. The purpose of interfaces is to allow you to generalise specific functionality regardless of implementation. You may have an
IDatabase
interface that has anOpen
/Close
method. The class that implements that interface may be connecting to a MySQL database or MS Access database. Irrespective of how it accomplishes this task, the goal is still the same...Open database, close database.Abstract classes are base classes that contain some abstract methods. They cannot be instantiated they are to be derived from. The purpose of an Abstract class is to allow you to define some generic functionality and sub-class to implement more specific functionality where appropriate.
So in summary, you should use interfaces when the implementation of each class differs completely. Use abstract classes when you have some similar behaviour but need to implement parts differently.
Hope that helps.
我想说,差异是语言相关的,但至少在 C++ 中,抽象类是实现接口的方式。
I would say that the difference is language dependent, but that in C++ at least, abstract classes are the means by which interfaces are implemented.
就求职面试而言,我一直听说关键一点是接口就是契约;接口就是契约。 接口虽然本身不实现它,但保证了功能。
As far as job interviews are concerned, I've always heard that the key point is that an interface is a contract; an interface, while not implementing it itself, guarantees functionality.