接口和抽象类 [英] Interface and abstract classes

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

问题描述

大家好,
我想知道,在您的类,可视化,接口和抽象类中实现这些元素的好处是什么.
我试图找出一个具体的原因,为什么我应该使用它们而不是直接去实现我的类.
Mninawa

Hi Everyone,
I would like to know, what is the advantage of implementing these elements in your classes,viz,interface and abstract classes.
Im trying to find out a concrete reason why should i used them instead of just go straight and implement my classes..
Mninawa

推荐答案

Mninawa,

通常,接口定义了一组类的接口,但没有提供有关实现方式的详细信息.通常用名称来强调此目的,例如IComparable和IEnumerable.

类通过提供实现接口中所有方法的方法来实现接口.一个类可以实现多个接口.

相比之下,抽象类是另一个类的基类-它既可以实现成员也可以实现抽象成员.它们通常用作框架的一部分,在框架中它们提供了一种行为模式,该行为模式有望通过派生自该行为的具体类来实现.

例如,一个类可以提供在屏幕上放置窗口的基本支持,但可以提供诸如Draw之类的抽象或虚拟方法,派生类应重写这些抽象或虚拟方法,以针对特定情况自定义行为.

但是,一个类只能从一个基类继承(在C#,Java等中).

但是,像Nishant一样,我强烈建议您学习更多有关此内容的信息-例如,GOF设计模式书中提供了大量示例,说明每种示例何时合适. 设计模式 [
Mninawa,

Generally, interfaces define the interface of a set of classes, but provide no detail of how that implementation is realised. This purpose is commonly emphasised by name, such as IComparable and IEnumerable.

A class implements an interface by providing methods that implement all the methods in the interface. A class may implement multiple interfaces.

By contrast, an abstract class is a base class of another class - it may have realised members as well as abstract members. They are commonly used as part of a framework, where they provide a pattern of behaviour that is expected to be realised by a concrete class deriving from it.

For example, a class may provide the basic support for putting a window on the screen, but provide abstract or virtual methods such as Draw, that should be overridden by derived classes to customise the behaviour to a particular situation.

A class may only inherit from one base class however (in C#, Java, etc.).

Like Nishant, however, I''d strongly recommend learning more about this - the GOF Design Patterns book for example gives plenty of examples of when each may be appropriate. Design Patterns[^]


如果不需要,则不要仅仅因为想要而使用接口或抽象基类.它们有特定的用途,除非您的方案适合那些使用方式,否则使用它们实际上是不好的设计.

另请阅读
http://msdn.microsoft.com/en-us/library /scsyfw1d(v=vs.71).aspx [ ^ ]
If you have no need to, then you should not use interfaces or abstract base classes merely because you want to. They have specific uses and unless your scenario fits those usage patterns, using them would actually be bad design.

Also read http://msdn.microsoft.com/en-us/library/scsyfw1d(v=vs.71).aspx[^]


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

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