java 为什么接口比抽象类更受欢迎?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/639592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why are interfaces preferred to abstract classes?
提问by Techmaddy
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:
我尝试给出一些答案,例如:
- We can get only one Extends functionality
- they are 100% Abstract
- Implementation is not hard-coded
- 我们只能得到一个扩展功能
- 他们是 100% 抽象的
- 实现不是硬编码的
They asked me take any of the JDBC api that you use. "Why are they Interfaces?".
他们让我使用您使用的任何 JDBC api。“为什么它们是接口?”。
Can I get a better answer for this?
我能得到更好的答案吗?
回答by DevinB
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.
该面试问题反映了提出问题的人的某种信念。我相信这个人是错的,因此你可以选择两个方向之一。
- Give them the answer they want.
- Respectfully disagree.
- 给他们想要的答案。
- 恭敬地不同意。
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.
接口有很多用途,并且有一个令人信服的理由相信它们“更好”。但是,您应该始终使用正确的工具来完成这项工作,这意味着您不能取消抽象类。
回答by TofuBeer
In general, and this is by no means a "rule" that should be blindly followed, the most flexible arrangement is:
总的来说,这绝不是盲目遵循的“规则”,最灵活的安排是:
interface
abstract class
concrete class 1
concrete class 2
The interface is there for a couple of reasons:
有这个界面有几个原因:
- an existing class that already extends something can implement the interface (assuming you have control over the code for the existing class)
- an existing class can be subclasses and the subclass can implement the interface (assuming the existing class is subclassable)
- 已经扩展了某些东西的现有类可以实现该接口(假设您可以控制现有类的代码)
- 现有类可以是子类,子类可以实现接口(假设现有类是可子类的)
This means that you can take pre-existing classes (or just classes that MUST extend from something else) and have them work with your code.
这意味着您可以使用预先存在的类(或只是必须从其他类扩展的类)并让它们与您的代码一起使用。
The abstract class is there to provide all of the common bits for the concrete classes. The abstract class is extended from when you are writing new classes or modifying classes that you want to extend it (assuming they extend from java.lang.Object).
抽象类为具体类提供所有公共位。当您编写新类或修改要扩展它的类(假设它们是从 java.lang.Object 扩展的)时,抽象类就会被扩展。
You should always (unless you have a really good reason not to) declare variables (instance, class, local, and method parameters) as the interface.
您应该始终(除非您有非常充分的理由不这样做)将变量(实例、类、本地和方法参数)声明为接口。
回答by Joel Coehoorn
You only get one shot at inheritance. If you make an abstract class rather than an interface, someone who inherits your class can't also inherit a different abstract class.
您只能获得一次继承权。如果你创建一个抽象类而不是一个接口,那么继承你类的人就不能继承另一个抽象类。
回答by Rowland Shaw
You can implement more than one interface, but you can only inherit from a single class
可以实现多个接口,但只能从一个类继承
回答by Warrior
Abstract Classes
抽象类
1.Cannot be instantiated independently from their derived classes. Abstract class constructors are called only by their derived classes.
1.不能独立于它们的派生类进行实例化。抽象类构造函数仅由其派生类调用。
2.Define abstract member signatures that base classes must implement.
2.定义基类必须实现的抽象成员签名。
3.Are more extensible than interfaces, without breaking any version compatibility. With abstract classes, it is possible to add additional nonabstract members that all derived classes can inherit.
3.比接口更具可扩展性,不破坏任何版本兼容性。对于抽象类,可以添加所有派生类都可以继承的其他非抽象成员。
4.Can include data stored in fields.
4.可以包括存储在字段中的数据。
5.Allow for (virtual) members that have implementation and, therefore, provide a default implementation of a member to the deriving class.
5.允许具有实现的(虚拟)成员,因此,为派生类提供成员的默认实现。
6.Deriving from an abstract class uses up a subclass's one and only base class option.
6.从抽象类派生使用了子类唯一的基类选项。
Interface
界面
1.Cannot be instantiated.
1.无法实例化。
2.Implementation of all members of the interface occurs in the base class. It is not possible to implement only some members within the implementing class.
2.接口的所有成员的实现都发生在基类中。不可能在实现类中只实现一些成员。
3.Extending interfaces with additional members breaks the version compatibility.
3.扩展接口增加成员破坏版本兼容性。
4.Cannot store any data. Fields can be specified only on the deriving classes. The workaround for this is to define properties, but without implementation.
4.不能存储任何数据。只能在派生类上指定字段。解决方法是定义属性,但没有实现。
5.All members are automatically virtual and cannot include any implementation.
5.所有成员都是自动虚拟的,不能包含任何实现。
6.Although no default implementation can appear, classes implementing interfaces can continue to derive from one another.
6.虽然不能出现默认实现,但实现接口的类可以继续从另一个类派生。
回答by toolkit
As devinband others mention, it sounds like the interviewer shows their ignorance in not accepting your valid answers.
正如devinb和其他人所提到的,这听起来像是面试官不接受你的有效答案表明他们的无知。
However, the mention of JDBC might be a hint. In that case, perhaps they are asking for the benefits of a clientcoding against an interface instead of a class.
但是,提到 JDBC 可能是一个提示。在这种情况下,也许他们要求客户端针对接口而不是类进行编码的好处。
So instead of perfectly valid answers such as "you only get one use of inheritance", which are relating to class design, they may be looking for an answer more like "decouples a client from a specific implementation".
因此,与类设计相关的完全有效的答案(例如“您只能使用一次继承”)不同,他们可能正在寻找更像是“将客户端与特定实现分离”的答案。
回答by Eddie
Abstract classes have a number of potential pitfalls. For example, if you override a method, the super()method is not called unless you explicitly call it. This can cause problems for poorly-implemented overriding classes. Also, there are potential problems with equals()when you use inheritance.
抽象类有许多潜在的缺陷。例如,如果您覆盖一个方法,super()除非您显式调用它,否则不会调用该方法。这可能会导致实现不佳的覆盖类出现问题。此外,equals()使用继承时存在潜在问题。
Using interfaces can encourage use of composition when you want to share an implementation. Composition is very often a better way to reuse others objects, as it is less brittle. Inheritance is easily overused or used for the wrong purposes.
当您想要共享一个实现时,使用接口可以鼓励使用组合。组合通常是重用其他对象的更好方法,因为它不那么脆弱。继承很容易被过度使用或用于错误的目的。
Defining an interface is a very safe way to define how an object is supposed to act, without risking the brittleness that cancome with extending another class, abstract or not.
定义一个接口是一个非常安全的定义对象应该如何行动,而不会危及该脆性方式可以配备扩展了另一个类,抽象的或没有。
Also, as you mention, you can only extend one class at a time, but you can implement as many interfaces as you wish.
此外,正如您所提到的,您一次只能扩展一个类,但您可以根据需要实现任意数量的接口。
回答by paulmurray
Abstract classes are used when you inherit implementation, interfaces are used when you inherit specification. The JDBC standards state that "A connection must do this". That's specification.
继承实现时使用抽象类,继承规范时使用接口。该JDBC标准状态“的连接必须做这个”。那是规范。
回答by Neal Stublen
"Why Interfaces are preferred over Abstract classes?"
“为什么接口比抽象类更受欢迎?”
The other posts have done a great job of looking at the differences between interfaces and abstract classes, so I won't duplicate those thoughts.
其他帖子在查看接口和抽象类之间的差异方面做得很好,所以我不会重复这些想法。
But looking at the interview question, the better question is really "Whenshould interfaces be preferred over abstract classes?" (and vice versa).
但是看看面试问题,更好的问题实际上是“什么时候接口比抽象类更受欢迎?” (反之亦然)。
As with most programming constructs, they're available for a reason and absolute statements like the one in the interview question tend to miss that. It sort of reminds me of all the statement you used to read regarding the gotostatement in C. "You should never use goto- it reveals poor coding skills." However, gotoalways had its appropriate uses.
与大多数编程结构一样,它们可用是有原因的,而面试问题中的绝对陈述往往会忽略这一点。这让我想起了你曾经读过的关于C 语言goto语句的所有语句。“你永远不应该使用goto- 它表明编码技能很差。” 然而,goto总是有其适当的用途。
回答by krosenvold
When you use abstract classes you create a coupling between the subclass and the base class. This coupling can sometimes make code really hard to change, especially as the number of subclasses increases. Interfaces do not have this problem.
当您使用抽象类时,您会在子类和基类之间创建耦合。这种耦合有时会使代码很难更改,尤其是当子类数量增加时。接口没有这个问题。
You also only have one inheritance, so you should make sure you use it for the proper reasons.
您也只有一个继承,因此您应该确保出于适当的原因使用它。

