这可能是一个通用的OOP问题。我想在接口和抽象类的使用基础上做一个通用的比较。
什么时候需要使用接口,什么时候需要使用抽象类?
这可能是一个通用的OOP问题。我想在接口和抽象类的使用基础上做一个通用的比较。
什么时候需要使用接口,什么时候需要使用抽象类?
当前回答
在Java中,您可以从一个(抽象)类继承来“提供”功能,并且可以实现许多接口来“确保”功能
其他回答
类只能继承自一个基类,因此如果您想使用抽象类为一组类提供多态性,它们必须全部继承自该类。抽象类也可以提供已经实现的成员。因此,您可以使用抽象类确保一定数量的相同功能,但不能使用接口。
下面是一些建议,可以帮助您决定是使用接口还是抽象类为组件提供多态性。
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
在Java中,您可以从一个(抽象)类继承来“提供”功能,并且可以实现许多接口来“确保”功能
1.如果您正在创建为不相关的类提供公共功能的东西,请使用接口。
2.如果您正在为层次结构中密切相关的对象创建一些东西,请使用抽象类。
答案因语言而异。例如,在Java中,一个类可以实现(继承)多个接口,但只能继承一个抽象类。所以接口给了你更多的灵活性。但在c++中却不是这样。
什么时候选择抽象类而不是接口?
如果计划在程序/项目的整个生命周期中更新基类,最好允许基类是一个抽象类 如果有人试图为层次结构中密切相关的对象构建主干,那么使用抽象类是非常有益的
什么时候选择接口而不是抽象类?
如果不需要处理大量的层次结构类型的框架,那么接口将是一个很好的选择 因为抽象类不支持多重继承(菱形问题),所以接口可以挽救局面