什么时候使用抽象类,什么时候使用接口 [英] when will use abstract class and when will use interface

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

问题描述



什么时候使用抽象类,什么时候使用接口,您可以给出样本

Hi,

when will use abstract class and when will use interface can you give sample

推荐答案

语录:

摘要和界面
•抽象类可以具有共享状态或功能.接口仅是提供状态或功能的承诺.一个好的抽象类将减少必须重写的代码量,因为它的功能或状态可以共享.该接口没有要共享的已定义信息.
•根源是抽象类确保所有后代共享功能/状态,而接口仅确保公共键.
•抽象类使您可以创建一个蓝图,并允许您额外构造所有后代要拥有的CONSTRUCT(实现)属性和方法.
•另一方面,接口仅允许您声明希望具有给定名称的属性和/或方法存在于实现该接口的所有类中,但未指定应如何实现.同样,一个类可以实现MANY接口,但只能扩展一个Abstract类.接口更像是一种高级架构工具
•为什么要一个使用另一个?前者允许对后代进行更具体的定义-后者允许更大的多态性.
•可以派生抽象类,而可以实现接口.两者之间有些区别.当您派生一个Abstract类时,派生类与基类之间的关系是是"关系.例如,狗是动物;绵羊是一种动物,这意味着派生类正在继承基类的某些属性.对于接口的实现,关系是可以".例如,狗可以是间谍狗.狗可以是马戏团狗.狗可以是竞赛狗.这意味着您实施某些方法来获取某些东西.

Abstract & Interface
• An abstract class can have shared state or functionality. An interface is only a promise to provide the state or functionality. A good abstract class will reduce the amount of code that has to be rewritten because its functionality or state can be shared. The interface has no defined information to be shared.
• Root point is that abstract classes ensure that all descendants share functionality/state, where an interface only ensures a common bond.
• Abstract classes allow you to create a blueprint, and allow you to additionally CONSTRUCT (implement) properties and methods you want ALL its descendants to possess.
• An interface on the other hand only allows you to declare that you want properties and/or methods with a given name to exist in all classes that implement it - but doesn''t specify how you should implement it. Also, a class can implement MANY interfaces, but can only extend ONE Abstract class. An Interface is more of a high level architectural tool
• Why use one over the other? The former allows for a more concrete definition of descendants - the latter allows for greater polymorphism.
• Abstract classes can be Derived whereas Interfaces can be Implemented. There is some difference between the two. When you derive an Abstract class, the relationship between the derived class and the base class is ''is a'' relationship. e.g., a Dog is an Animal; a Sheep is an Animal which means that a Derived class is inheriting some properties from the base class. Whereas for implementation of interfaces, the relationship is "can be". e.g., a Dog can be a spy dog. A dog can be a circus dog. A dog can be a race dog. This means that you implement certain methods to acquire something.




本文可以为您提供帮助:
抽象类与接口 [
Hi,

This article can help you:
Abstract Class versus Interface[^]


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

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