接口优于抽象类的优势是什么? [英] what is the advantage of interface over abstract classes?

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

问题描述

抽象类具有具体和抽象功能。
接口只有抽象函数。

Abstract class have both concrete and abstract function . interface only have abstract functions.

两者都可以覆盖。是

一个人的实时优势是什么?

What is the real time advantage of one over the other ?

推荐答案

当你想说我不在乎你怎么做,但这就是你需要完成的事情。

Interfaces are for when you want to say "I don't care how you do it, but here's what you need to get done."

抽象类当你想说我知道你应该做什么,我知道你应该如何在一些/很多情况下这样做。

Abstract classes are for when you want to say "I know what you should do, and I know how you should do it in some/many of the cases."

抽象类有一些严重的缺点。例如:

Abstract classes have some serious drawbacks. For example:

class House {

}

class Boat {

}

class HouseBoat extends /* Uh oh!! */ {
    // don't get me started on Farmer's Insurance "Autoboathome" which is also a helicopter
}

您可以通过界面获得:

interface Liveable {

}

interface Floatable {

}

class HouseBoat implements Liveable, Floatable {

}

现在,抽象类也非常有用。例如,考虑AbstractCollection类。它为所有集合定义了非常常见的方法的默认行为,例如 isEmpty()包含(Object)。如果您愿意,可以覆盖这些行为,但是...是确定集合是否为空的行为确实可能会发生变化?通常它会是 size == 0

Now, abstract classes are also very useful. For example, consider the AbstractCollection class. It defines the default behavior for very common methods to all Collections, like isEmpty() and contains(Object). You can override these behaviors if you want to, but... is the behavior for determining if a collection is empty really likely to change? Typically it's going to be size == 0.

因为它不会经常改变,它真的是值得开发人员的时间来实现该方法的每一个...单个...时间...对于已解决类别中的每个方法?更不用说当你需要对它进行更改时,如果你不得不在任何地方重新实现它,你将会遇到代码重复和错过的错误。

And since it won't change often, is it really worth the developer's time to implement that method every... single... time... for every method in that "solved" category? Not to mention when you need to make a change to it, you're going to have code duplication and missed bugs if you had to re-implement it everywhere.

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

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