抽象类和接口之间的主要区别是什么?
根据最近的采访趋势,我注意到这个问题每次都会出现。但是,当一个人回答一般定义时,面试官会说每个人都知道……讲一些不同的东西。进一步的场景会被问到哪些场景将被使用并且有益,以及为什么
所以请分享对此主题的任何新见解。
提前致谢...
In context of recent trends in interviews i have noticed that this question arises every time. But when one answers the general definition then the interviewer says everyone knows it... tell something different. Further scenarios are asked where which one will be used and be beneficial and why
So kindly share any new insight into this topic.
Thanks in advance...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
抽象类可以定义方法的基本实现以及受保护或私有的数据成员,而接口仅定义类必须与公共数据成员一起提供的功能。
我喜欢这样看待它:抽象类是其他类的基础。它不仅指定特定事物系列必须具有的操作,还指定这些操作完成其工作所需的数据。特定的子项可以添加(甚至忽略,如果需要)特定的数据元素。另一方面,界面是一份契约——它没有说明你将如何做某事,只说明你必须做什么以及你将让外界看到什么。您的内部运作是您在界面中自己的事情。
An abstract class can define base implementations of methods along with data members that are protected or private, while an interface only defines the functionality that a class must provide along with public data members.
The way I like to look at it is that an abstract class is a foundation for other classes. It not only specifies the operations that a specific family of things has to have, but also the data that these operations need to do their work. Specific children can add (or even ignore, if needed) specific data elements. An interface, on the other hand, is a contract - it says nothing about how you are going to do something, only what things you must do and what you will make visible to the outside world. Your inner workings are your own business in an interface.
抽象类可以为其方法提供实现,而接口严格提供契约(对象必须实现哪些方法)。
当您想要为继承者提供基本实现但又不想直接创建类的实例时,抽象类非常有用。例如,考虑一辆车。您不想创建通用汽车,但每个护理都可以共享一些基本功能集:
当您有一些可能彼此不直接相关的类,但您希望以相同的方式处理时,接口非常有用,因为每个都有一组相似的功能。
Abstract classes can provide implementations for their methods whereas an Interface strictly provides a contract (what methods an object must implement).
Abstract classes are useful in situations where you want to provide a base implementation to inheritors but you don't want an instance of your class created directly. For example, think about a car. You wouldn't want to create a generic car, but each care can share some base set of functionality:
Interfaces are useful when you have some classes that may not be directly related to each other, but you want to treat in the same fashion because each has a similar set of functionality.
除了其他人所说的之外,我将接口视为跨类常见但不属于 is-a 关系的行为关系。它是一种表达常见行为的方式,而不是继承 is-a 关系。我相信这就是为什么有些人称接口为穷人的多重继承。
In addition to what the others have said, I look at an interface as a relationship of behaviors that are common across classes but are not in the is-a relationship. It is a way of expressing common behaviors as opposed to the inheritance of the is-a relationships. I believe this is why some call interfaces a poor man's multiple inheritance.