What's the difference between an interface and an abstract class? [duplicate]

烈酒焚心 提交于 2019-12-29 02:08:21

问题


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).


回答1:


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.




回答2:


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.




回答3:


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 an Open/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.




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/681602/whats-the-difference-between-an-interface-and-an-abstract-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!