这可能是一个通用的OOP问题。我想在接口和抽象类的使用基础上做一个通用的比较。
什么时候需要使用接口,什么时候需要使用抽象类?
这可能是一个通用的OOP问题。我想在接口和抽象类的使用基础上做一个通用的比较。
什么时候需要使用接口,什么时候需要使用抽象类?
当前回答
车辆包括汽车、坦克、飞机、手推车等。
抽象类Vehicle可以有子类,如car、tank、plane、cart等。
public abstract Vehicle {...}
public Car extends Vehicle {...}
public Tank extends Vehicle {...}
那么,什么是可移动的?几乎一切! 然后
石头,蛋糕,汽车,行星,星系,甚至你都是可移动的!
它们中的大多数也是可观察的!
什么是可吃的?这是一款名为《美味星球》的游戏。 然后
石头,汽车,行星,星系,甚至时间!
public interface Movable {...}
public interface Observable {...}
public interface Eatable {...}
public class Stone implements Movable, Eatable, Observable {...}
public class Time implements Eatable, Observable {...}
public class Stupidity implements Observable {...}
终于!
public class ChocolateCar extends Vehicle implements Eatable {...}
其他回答
类只能继承自一个基类,因此如果您想使用抽象类为一组类提供多态性,它们必须全部继承自该类。抽象类也可以提供已经实现的成员。因此,您可以使用抽象类确保一定数量的相同功能,但不能使用接口。
下面是一些建议,可以帮助您决定是使用接口还是抽象类为组件提供多态性。
If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created in that way. If a new version of an interface is required, you must create a whole new interface. If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes. If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class. If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
抄袭: http://msdn.microsoft.com/en-us/library/scsyfw1d%28v=vs.71%29.aspx
如果下列语句适用于您的情况,请考虑使用抽象类:
您希望在几个密切相关的类之间共享代码。 您希望扩展抽象类的类具有许多公共方法或字段,或者需要除public以外的访问修饰符(例如protected和private)。 您希望声明非静态或非final字段。这使您能够定义可以访问和修改其所属对象状态的方法。
如果这些语句适用于您的情况,请考虑使用接口:
您希望不相关的类实现您的接口。例如,Comparable和Cloneable接口是由许多不相关的类实现的。 您希望指定特定数据类型的行为,但不关心由谁实现其行为。 您希望利用多个继承。
源
好吧,我自己刚刚“grokup”了这个——这是外行的术语(如果我错了,请随意纠正我)——我知道这个话题太老了,但其他人可能有一天会偶然发现它……
抽象类允许你创建一个蓝图,并允许你额外构造(实现)属性和方法,你希望它的所有后代都拥有。
另一方面,接口只允许您声明希望在实现它的所有类中存在具有给定名称的属性和/或方法——但不指定应该如何实现它。同样,一个类可以实现许多接口,但只能扩展一个抽象类。界面更像是一种高级架构工具(如果你开始掌握设计模式,这一点就会变得更清楚)——抽象则同时涉足这两个阵营,也可以执行一些繁琐的工作。
为什么使用其中一种而不是另一种呢?前者允许对后代进行更具体的定义,而后者允许更大的多态性。最后一点对最终用户/编码器很重要,他们可以利用这些信息以各种组合/形状来实现A.P.I(界面),以满足他们的需求。
我认为这对我来说是一个“顿悟”的时刻——少从作者的角度来考虑接口,多从后面加入到项目中实现或扩展API的编码器的角度来考虑接口。
这是一个很难打的电话。
我可以给出一个提示:一个对象可以实现许多接口,而一个对象只能继承一个基类(在像c#这样的现代OO语言中,我知道c++有多个继承-但这不是不受欢迎吗?)
简单的回答是:抽象类允许您创建子类可以实现或覆盖的功能。接口只允许您定义功能,而不能实现它。虽然一个类只能扩展一个抽象类,但它可以利用多个接口。