为什么接口更喜欢抽象类? [英] Why are interfaces preferred to abstract classes?

查看:147
本文介绍了为什么接口更喜欢抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近参加了一次采访,他们向我问了一个问题为什么接口比抽象类更受欢迎?

I recently attended an interview and they asked me the question "Why Interfaces are preferred over Abstract classes?"

我尝试给出一些答案,如:

I tried giving a few answers like:


  • 我们只能获得一个扩展功能

  • 他们是100%抽象

  • 实现不是硬编码的

他们让我选择你使用的任何JDBC api。 为什么他们是接口?。

They asked me take any of the JDBC api that you use. "Why are they Interfaces?".

我可以得到更好的答案吗?

Can I get a better answer for this?

推荐答案

面试问题反映了提问者的某种信念。我相信这个人是错的,因此你可以选择其中一个方向。

That interview question reflects a certain belief of the person asking the question. I believe that the person is wrong, and therefore you can go one of two directions.


  1. 给他们想要的答案。

  2. 恭敬地不同意。

他们想要的答案,嗯,其他海报突出了那些令人难以置信的好。
多接口继承,继承强制类进行实现选择,接口可以更容易更改。

The answer that they want, well, the other posters have highlighted those incredibly well. Multiple interface inheritance, the inheritance forces the class to make implementation choices, interfaces can be changed easier.

但是,如果你创建一个引人注目的(并且正确)你的意见分歧,然后面试官可能会注意到。
首先,突出显示有关接口的积极信息,这是必须的。
其次,我会说在许多情况下界面更好,但它们也导致代码重复,这是一个负面的事情。如果你有一个广泛的子类,它们将在很大程度上执行相同的实现,加上额外的功能,那么你可能需要一个抽象类。它允许您拥有许多具有细粒度细节的类似对象,而只有接口,您必须拥有许多不同的对象,几乎重复的代码。

However, if you create a compelling (and correct) argument in your disagreement, then the interviewer might take note. First, highlight the positive things about interfaces, this is a MUST. Secondly, I would say that interfaces are better in many scenarios, but they also lead to code duplication which is a negative thing. If you have a wide array of subclasses which will be doing largely the same implementation, plus extra functionality, then you might want an abstract class. It allows you to have many similar objects with fine grained detail, whereas with only interfaces, you must have many distinct objects with almost duplicate code.

界面有很多用途,有令人信服的理由相信它们更好。但是,您应该始终使用正确的工具来完成工作,这意味着您无法注销抽象类。

Interfaces have many uses, and there is a compelling reason to believe they are 'better'. However you should always be using the correct tool for the job, and that means that you can't write off abstract classes.

这篇关于为什么接口更喜欢抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆