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

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

问题描述

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

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天全站免登陆