界面与抽象类(通用OO)

最近有两次电话采访,我被问及界面和抽象类之间的区别。 我已经解释了他们所能想到的每一个方面,但似乎他们正在等待我提到一些具体的东西,我不知道它是什么。

从我的经验来看,我认为以下是事实。 如果我错过了一个重点,请让我知道。

接口:

在接口中声明的每个方法都必须在子类中实现。 接口中只有事件,委托,属性(C#)和方法可以存在。 一个类可以实现多个接口。

抽象类:

只有抽象方法必须由子类实现。 一个抽象类可以有实现的普通方法。 抽象类也可以在事件,委托,属性和方法旁边有类variables。 一个类只能由于C#中多重inheritance的不存在才能实现一个抽象类。

  1. 毕竟,面试官想出了这样一个问题:“如果抽象类只有抽象方法,那么接口又有什么不同呢? 我不知道答案,但我认为这是上面提到的inheritance权吗?

  2. 另一位面试官问我,如果你在界面中有一个公共variables,那么和抽象类有什么不同呢? 我坚持你不能在一个接口中有一个公共variables。 我不知道他想听什么,但他也不满意。

另见

  • 何时使用接口而不是抽象类,反之亦然

  • 接口与抽象类

  • 你如何决定使用抽象类和接口?

  • 界面和抽象类有什么区别?

虽然你的问题表明这是“一般OO”,但它确实似乎是关注.NET使用这些术语的。

在.NET中(类似于Java):

  • 接口可以没有状态或实现
  • 一个实现接口的类必须提供该接口所有方法的实现
  • 抽象类可能包含状态(数据成员)和/或实现(方法)
  • 抽象类可以在不实现抽象方法的情况下被inheritance(尽pipe这样的派生类本身是抽象的)
  • 接口可能是多重inheritance的,抽象类可能不会(这可能是接口与abtract类分开存在的关键具体原因 – 它们允许实现多inheritance,从而消除了一般MI的许多问题)。

作为一般的OO术语,差异不一定是明确的。 例如,有些C ++程序员可能持有类似的严格定义(接口是不能包含实现的抽象类的严格子集),而有些人可能会说,具有某些默认实现的抽象类仍然是一个接口,或者是一个非抽象类仍然可以定义一个接口。

事实上,有一种称为非虚拟接口(NVI)的C ++习惯用法,其中公共方法是非虚拟方法,可以“虚拟”到私有虚拟方法:

怎么样呢?我在空军的时候,我去飞行员训练,成为美国空军的飞行员。 那时我没有资格飞行任何东西,不得不参加飞机型的训练。 一旦我有资格,我是一个飞行员(抽象类)和一个C-141飞行员(具体类)。 在我的一项任务中,我被赋予了一个额外的职责:安全官员。 现在我还是一名飞行员和一名C-141飞行员,但是我也执行了安全官员的职责(可以这么说我实施了ISafetyOfficer)。 一名飞行员不需要担任安全官,其他人也可以这样做。

美国空军的所有飞行员都必须遵守空军的一些规定,所有的C-141(或F-16或T-38)飞行员都是美国空军的飞行员。 任何人都可以成为安全人员。 所以,总结一下:

  • 试点:抽象类
  • C-141试点:具体类
  • ISafety官员:接口

补充说明:这是为了帮助解释这个概念,而不是编码build议。 看到下面的各种评论,讨论很有趣。

我认为他们正在寻找的答案是OPPS的基本哲学差异。

当派生类共享抽象类的核心属性和行为时使用抽象类inheritance。 实际定义类的行为types。

另一方面,当类共享外围设备行为时使用接口inheritance,而不一定定义派生类。

例如。 汽车和卡车共享汽车抽象类的许多核心属性和行为,但是它们也共享一些外围行为,例如生成排气,即使像Drillers或PowerGenerators这样的非汽车类也共享,并且不一定定义汽车或卡车所以,汽车,卡车,司钻和PowerGenerator都可以共享相同的界面IExhaust。

简而言之:抽象类用于对相似类的类进行build模 (例如,Animal可以是抽象类,Human,Lion,Tiger可以是具体的派生类)

接口用于2个相似/不相似的类之间的通信 ,它不关心实现接口的类的types(例如,Height可以是接口属性,可以由Human,Building,Tree来实现,不pipe你是否可以吃,你可以游泳,你可以死或任何东西..它只是一个事情,你需要有高度(在你的课实施))。

还有一些其他的区别 –

接口不能有任何具体的实现。 抽象基类可以。 这允许你在那里提供具体的实现。 这可以让一个抽象的基类实际上提供更严格的契约,而一个接口实际上只描述一个类是如何使用的。 (抽象基类可以有非虚拟成员来定义行为,从而给予基类作者更多的控制。)

一个类可以实现多个接口。 一个类只能从一个抽象基类派生。 这允许使用接口的多态层次结构,但不允许抽象基类。 这也允许使用接口的伪多inheritance。

抽象基类可以在v2 +中修改而不会中断API。 接口的改变正在改变。

[C#/ .NET特定]与抽象基类不同,接口可以应用于值types(结构)。 结构不能从抽象基类inheritance。 这允许将行为契约/使用准则应用于价值types。

遗产
考虑一辆汽车和一辆公共汽车。 他们是两种不同的车辆。 但是他们仍然有一些共同的特性,比如他们有一个转向系统,刹车,齿轮,发动机等。
因此,inheritance概念可以表示如下。

 public class Vehicle { private Driver driver; private Seat[] seatArray; //In java and most of the Object Oriented Programming(OOP) languages, square brackets are used to denote arrays(Collections). //You can define as many properties as you want here.. } 

现在一辆自行车..

 public class Bicycle extends Vehicle { //You define properties which are unique to bicycles here.. private Pedal pedal; } 

和一辆车

 public class Car extends Vehicle { private Engine engine; private Door[] doors; } 

这就是inheritance 。 我们使用它们将对象分类为更简单的基本forms及其子项,如上所述。

抽象类

抽象类是不完整的对象。 为了进一步理解,我们再次考虑车辆类比。
一辆车可以驾驶。 对? 但是,不同的车辆以不同的方式驾驶。例如,您不能像驾驶自行车一样驾驶汽车。
那么如何performance一辆车的驱动function呢? 很难检查它是什么types的车辆,并用它自己的function来驱动车辆。 在添加新型车辆时,您将不得不一次又一次更改驾驶员类别。
这里是抽象类和方法的作用。 您可以将驱动器方法定义为抽象,以告诉每个inheritance的子项必须实现此function。
所以如果你修改车辆类

 //......Code of Vehicle Class abstract public void drive(); //.....Code continues 

自行车和汽车还必须指定如何驾驶它。 否则,代码将不会编译并引发错误。
简而言之,抽象类是一个部分不完整的类,具有一些不完整的function,inheritance的子类必须指定它们自己的类。

接口接口是完全不完整的。 他们没有任何财产。 他们只是表明,inheritance孩子是有能力的事情..
假设你有不同types的手机。 他们每个人都有不同的方式来做不同的function; 例如:打电话给一个人。 电话制造商指定了如何做到这一点。 这里的手机可以拨打一个号码 – 也就是拨号。 我们将其表示为一个接口。

 public interface Dialable { public void dial(Number n); } 

这里Dialable的制造商定义了如何拨号。 你只需要给它一个号码拨打。

 Dialable myPhone1 = new Dialable() { public void dial(Number n) { //Do the phone1's own way to dial a number } } Dialable myPhone2 = new Dialable() { public void dial(Number n) { //Do the phone2's own way to dial a number } } 

在这里通过使用接口而不是抽象类,您不必担心它的属性。 例如:是否有触摸屏或拨号盘,是固定的固定电话还是手机。 你只需要知道它是否可以拨打; 它是否inheritance(或实现)Dialable接口。
接口通常被开发人员用来确保对象之间的互操作性(可互换使用),只要它们共享一个共同的function(就像你可以转换到固定电话或移动电话一样,只要你需要拨打一个号码)。 简而言之,接口是非常简单的抽象类的版本,没有任何属性。
还要注意,你可以实现(inheritance)尽可能多的接口,但是你只能扩展(inheritance)一个父类。

更多信息 抽象类与接口

如果你认为java是OOP语言来回答这个问题的话,那么Java 8的发布会导致上述答案中的一些内容过时。 现在java接口可以有具体实现的默认方法。

Oracle 网站提供了interfaceabstract类之间的关键区别。

考虑使用抽象类如果:

  1. 你想在几个密切相关的类中分享代码。
  2. 您期望扩展抽象类的类具有许多常用的方法或字段,或者需要公共访问修饰符(例如protected和private)。
  3. 您想要声明非静态或非最终字段。

考虑使用接口如果:

  1. 你期望不相关的类将实现你的接口。 例如,许多不相关的对象可以实现Serializable接口。
  2. 您想要指定特定数据types的行为,但不关心谁实现其行为。
  3. 你想利用types的多重inheritance。

简单来说,我想用

接口:通过多个不相关的对象来实现合同

抽象类:在多个相关对象之间实现相同或不同的行为

看看代码示例以清楚的方式理解事情: 我应该如何解释接口和Abstract类之间的区别?

通过实现接口,你正在实现组合(“有一个”关系),而不是inheritance(“是一个”关系)。 当需要使用接口来实现行为组合而不是inheritance的devise模式时,这是一个重要的原则。

采访者正在咆哮一棵奇树。 对于像C#和Java这样的语言来说,是有区别的,但在其他语言如C ++中则没有。 OO理论不区分二者,仅仅是语言的语法。

抽象类是具有实现和接口(纯虚拟方法)的类,将被inheritance。 接口通常没有任何实现,只有纯虚函数。

在C#或Java中,没有任何实现的抽象类与仅用于inheritance它的语法的接口不同,只能从一个inheritance。

我将解释接口和抽象类的深度细节。如果您了解接口和抽象类的概述,那么当我们应该使用接口和何时应该使用抽象类时,第一个问题会到达您的想法。 所以请查看下面的Interface和Abstract类的解释。

  1. 当我们应该使用接口?

    如果你不知道实现只是我们有需求规格,然后我们去接口

  2. 什么时候应该使用抽象类?

    如果你知道实现,但不完全(部分实现),那么我们去抽象类。

    接口

    每种方法默认的公共抽象手段接口是100%纯粹的抽象。

    抽象

    可以有具体方法和抽象方法,什么是具体方法,在Abstract类中有实现,抽象类是声明为抽象的类 – 它可能包含也可能不包含抽象方法。

    接口

    我们不能将接口声明为私有的,受保护的

    问:为什么我们没有声明Interface是一个私有的并且受保护的?

    因为默认的接口方法是公共抽象的,所以我们不把接口声明为私有和保护的原因。

    接口方法
    我们也不能将接口声明为private,protected,final,static,synchronized,native …..

    我将给出原因:为什么我们不声明同步的方法,因为我们不能创build接口的对象和同步工作的对象所以和儿子的原因,我们没有声明同步的方法瞬态概念也不适用,因为暂时的工作与同步。

    抽象

    我们很高兴地使用公共的,私人的最终静态….意味着没有限制适用于抽象。

    接口

    variables在Interface中声明为默认的public static final,所以我们也没有声明variables为private,protected。

    variables修饰符也不适用于接口,因为接口variables默认为public static final和finalvariables,一旦将variables赋值给variables,一旦将variables声明为variables,就必须赋值variables。

    而volatilevariables是不断变化的,所以是opp。 到最后是因为我们在界面中没有使用volatilevariables。

    抽象

    抽象variables不需要声明public static final。

我希望这篇文章是有用的。

对于.Net,

你的答案第二个采访者也是第一个答案…抽象类可以有实现,AND状态,接口不能…

编辑:在另一个说明,我甚至不会使用短语“子类”(或“inheritance”短语)来描述“定义来实现”一个接口的类。 对我来说,一个接口是一个合约的定义,如果一个类被定义为“实现”那个接口,那么它就必须符合这个合约。 它不会inheritance任何东西…您必须明确地自行添加所有内容。

从概念上讲,保持语言特定的实现,规则,好处,并通过使用任何人或两者来实现任何编程目标,可以或不能有代码/数据/属性,等等,单一或多重inheritance

1-抽象(或纯粹的抽象)类是实现层次结构的手段。 如果您的业务对象在结构上看起来有点相似,那么只会使用inheritance/抽象类来表示父级子级(层次结构)types的关系。 如果你的业务模型没有层次结构,那就不应该使用inheritance(这里我不是谈论编程逻辑,例如一些devise模式需要inheritance)。 从概念上讲,抽象类是一种在OOP中实现业务模型层次结构的方法,与接口无关,实际上把抽象类和接口进行比较是没有意义的,因为两者在概念上是完全不同的东西,只是在面试中要求检查因为在执行过程中,它们看起来都提供了相同的function,程序员通常更多地强调编码。 [记住这一点,抽象是不同于抽象类]。

2-接口是一个合同,一个完整的业务function由一组function所代表。 这就是为什么它被实现,而不是inheritance。 业务对象(不pipe是否是层次结构的一部分)可以具有任意数量的完整业务function。 它与抽象类无关,一般意味着inheritance。 例如,一个人可以运行,一个大象可以运行,一个小鸟可以运行等等,所有这些不同层次的对象都会实现RUN界面或EAT或SPEAK界面。 不要进入实现,因为您可能将其实现为具有实现这些接口的每种types的抽象类。 任何层次结构的对象都可以具有与其层次无关的function(接口)。

我相信,接口不是为了实现多重inheritance或暴露公共行为而发明的,类似地,纯粹的抽象类不是要超越规则接口,而是接口是一个对象可以做的function(通过那个接口的function),抽象类表示产生具有父母的核心结构(属性+function)的孩子的层级的父母

当你被问及差别时,除非明确询问,否则它实际上是概念上的差异,而不是语言特定实现的差异。

我相信,两位采访者都期待着这两者之间有一条直线上的差异,当你失败时,他们试图通过实施一个ONE来驱使你这个差异

如果你只有一个抽象类只有抽象方法呢?

我认为他们不喜欢你的回答,因为你给出了技术上的差异,而不是devise上的差异。 这个问题就像是一个巨魔问题。 事实上,接口和抽象类有一个完全不同的性质,所以你不能真正地比较它们。 我会告诉你我的界面是什么angular色,抽象类的作用是什么。

接口:用于确保合同,并使类之间的低耦合,以便有一个更可维护,可扩展和可testing的应用程序。

抽象类:仅用于分解相同责任的类之间的一些代码。 请注意,这是多重inheritance在OOP中是一件坏事的主要原因,因为一个类不应该处理许多责任 (使用组合 )。

因此,接口具有真正的架构angular色,而抽象类几乎只是实现的细节(当然,如果您正确使用它的话)。

 After all that, the interviewer came up with the question "What if you had an Abstract class with only abstract methods? How would that be different from an interface?" 

Docs清楚地表明,如果一个抽象类仅包含抽象方法声明,则应该声明为一个接口。

 An another interviewer asked me what if you had a Public variable inside the interface, how would that be different than in Abstract Class? 

Interfaces中的variables默认为public static和final。 如果抽象类中的所有variables都是公开的,那么问题就可以被定义为? 那么他们仍然可以是非静态的,非终极的,不像界面中的variables。

最后,我会再添加一点到上面提到的那些 – 抽象类仍然是类,并落在一个inheritance树中,而接口可以存在于多重inheritance中。

  1. 接口:
    • 我们不实现(或定义)方法,我们在派生类中实现。
    • 我们不在接口中声明成员variables。
    • 接口表示HAS-A关系。 这意味着他们是一个对象的面具。
  2. 抽象类:
    • 我们可以在抽象类中声明和定义方法。
    • 我们隐藏它的构造函数。 这意味着没有直接创build的对象。
    • 抽象类可以保存成员variables。
    • 派生类inheritance到抽象类,意味着来自派生类的对象不被屏蔽,它inheritance到抽象类。 这种情况下的关系是IS-A。

这是我的意见。

由Jeffrey Richter通过C#复制CLR

我经常听到这个问题:“我应该devise一个基本types还是一个接口?”答案并不总是清晰的。

这里有一些指导方针可以帮助你:

■IS-A与CAN-DO的关系一个types只能inheritance一个实现。 如果派生types不能声明与基types的IS-A关系,则不要使用基types; 使用一个接口。 接口意味着CAN-DO关系。 如果CAN-DOfunction似乎属于各种对象types,请使用接口。 例如,一个types可以将自身的实例转换为另一个types(IConvertible),一个types可以序列化自己的一个实例(ISerializable)等等。注意值types必须从System.ValueType派生,因此不能派生从一个任意的基类。 在这种情况下,您必须使用CAN-DO关系并定义一个接口。

■■易于使用作为开发人员,定义从基本types派生的新types比实现接口的所有方法通常更容易。 基types可以提供很多function,所以派生types可能只需要对其行为进行相对较小的修改。 如果你提供一个接口,新的types必须实现所有的成员。

一致的实施不pipe接口合同有多好logging,每个人都不太可能正确执行合同。 事实上,COM遭受这个问题,这就是为什么一些COM对象只能在Microsoft Word或Windows Internet Explorer中正常工作。 通过提供一个良好的默认实现的基本types,你开始使用一个有效的types,并经过良好testing; 您可以修改需要修改的部分。

版本控制如果向基本types添加方法,派生types会inheritance新方法,您可以使用可用的types开始,甚至不必重新编译用户的源代码。 Adding a new member to an interface forces the inheritor of the interface to change its source code and recompile.

Difference between Java Interface and Abstract Class

  1. Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.

  2. Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.

  3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..

  4. Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.

  5. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.

  6. A Java class can implement multiple interfaces but it can extend only one abstract class.

  7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.

  8. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.

Most answers focus on the technical difference between Abstract Class and Interface, but since technically, an interface is basically a kind of abstract class (one without any data or implementation), I think the conceptual difference is far more interesting, and that might be what the interviewers are after.

An Interface is an agreement . It specifies: "this is how we're going to talk to each other". It can't have any implementation because it's not supposed to have any implementation. It's a contract. It's like the .h header files in C.

An Abstract Class is an incomplete implementation . A class may or may not implement an interface, and an abstract class doesn't have to implement it completely. An abstract class without any implementation is kind of useless, but totally legal.

Basically any class, abstract or not, is about what it is , whereas an interface is about how you use it . For example: Animal might be an abstract class implementing some basic metabolic functions, and specifying abstract methods for breathing and locomotion without giving an implementation, because it has no idea whether it should breathe through gills or lungs, and whether it flies, swims, walks or crawls. Mount , on the other hand, might be an Interface, which specifies that you can ride the animal, without knowing what kind of animal it is (or whether it's an animal at all!).

The fact that behind the scenes, an interface is basically an abstract class with only abstract methods, doesn't matter. Conceptually, they fill totally different roles.

Abstract class And Interface Difference :

  1. Abstract class can have abstract and non-abstract methods and Interface can have only abstract methods.
  2. Abstract class doesn't support multiple inheritance And Interface supports multiple inheritance.
  3. Abstract class can have final, non-final, static and non-static variables And Interface has only static and final variables.
  4. Abstract class can have static methods, main method and constructor And Interface can't have static methods, main method or constructor.
  5. Abstract class can provide the implementation of interface And Interface can't provide the implementation of abstract class.
  6. The abstract keyword is used to declare abstract class And The interface keyword is used to declare interface.
  7. Abstract class achieves partial abstraction (0 to 100%) because there are non abstract methods also in abstract class whereas interface achieves fully abstraction (100%).

Interfaces are light weight way to enforce a particular behavior. That is one way to think of.

An interface defines a contract for a service or set of services. They provide polymorphism in a horizontal manner in that two completely unrelated classes can implement the same interface but be used interchangeably as a parameter of the type of interface they implement, as both classes have promised to satisfy the set of services defined by the interface. Interfaces provide no implementation details.

An abstract class defines a base structure for its sublcasses, and optionally partial implementation. Abstract classes provide polymorphism in a vertical, but directional manner, in that any class that inherits the abstract class can be treated as an instance of that abstract class but not the other way around. Abstract classes can and often do contain implementation details, but cannot be instantiated on their own- only their subclasses can be "newed up".

C# does allow for interface inheritance as well, mind you.

1) An interface can be seen as a pure Abstract Class, is the same, but despite this, is not the same to implement an interface and inheriting from an abstract class. When you inherit from this pure abstract class you are defining a hierarchy -> inheritance, if you implement the interface you are not, and you can implement as many interfaces as you want, but you can only inherit from one class.

2) You can define a property in an interface, so the class that implements that interface must have that property.

例如:

  public interface IVariable { string name {get; set;} } 

The class that implements that interface must have a property like that.

As you might have got the theoretical knowledge from the experts, I am not spending much words in repeating all those here, rather let me explain with a simple example where we can use/cannot use Interface and Abstract class .

Consider you are designing an application to list all the features of Cars. In various points you need inheritance in common, as some of the properties like DigitalFuelMeter, Air Conditioning, Seat adjustment, etc are common for all the cars. Likewise, we need inheritance for some classes only as some of the properties like the Braking system (ABS,EBD) are applicable only for some cars.

The below class acts as a base class for all the cars:

 public class Cars { public string DigitalFuelMeter() { return "I have DigitalFuelMeter"; } public string AirCondition() { return "I have AC"; } public string SeatAdjust() { return "I can Adjust seat"; } } 

Consider we have a separate class for each Cars.

 public class Alto : Cars { // Have all the features of Car class } public class Verna : Cars { // Have all the features of Car class + Car need to inherit ABS as the Braking technology feature which is not in Cars } public class Cruze : Cars { // Have all the features of Car class + Car need to inherit EBD as the Braking technology feature which is not in Cars } 

Consider we need a method for inheriting the Braking technology for the cars Verna and Cruze (not applicable for Alto). Though both uses braking technology, the "technology" is different. So we are creating an abstract class in which the method will be declared as Abstract and it should be implemented in its child classes.

 public abstract class Brake { public abstract string GetBrakeTechnology(); } 

Now we are trying to inherit from this abstract class and the type of braking system is implemented in Verna and Cruze:

 public class Verna : Cars,Brake { public override string GetBrakeTechnology() { return "I use ABS system for braking"; } } public class Cruze : Cars,Brake { public override string GetBrakeTechnology() { return "I use EBD system for braking"; } } 

See the problem in the above two classes? They inherit from multiple classes which C#.Net doesn't allow even though the method is implemented in the children. Here it comes the need of Interface.

 interface IBrakeTechnology { string GetBrakeTechnology(); } 

And the implementation is given below:

 public class Verna : Cars, IBrakeTechnology { public string GetBrakeTechnology() { return "I use ABS system for braking"; } } public class Cruze : Cars, IBrakeTechnology { public string GetBrakeTechnology() { return "I use EBD system for braking"; } } 

Now Verna and Cruze can achieve multiple inheritance with its own kind of braking technologies with the help of Interface.

From another answer of mine , mostly dealing with when to use one versus the other:

In my experience, interfaces are best used when you have several classes which each need to respond to the same method or methods so that they can be used interchangeably by other code which will be written against those classes' common interface. The best use of an interface is when the protocol is important but the underlying logic may be different for each class. If you would otherwise be duplicating logic, consider abstract classes or standard class inheritance instead.

Though this question is quite old, I would like to add one other point in favor of interfaces:

Interfaces can be injected using any Dependency Injection tools where as Abstract class injection supported by very few.

Interface Types vs. Abstract Base Classes

Adapted from the Pro C# 5.0 and the .NET 4.5 Framework book.

The interface type might seem very similar to an abstract base class. Recall that when a class is marked as abstract, it may define any number of abstract members to provide a polymorphic interface to all derived types. However, even when a class does define a set of abstract members, it is also free to define any number of constructors, field data, nonabstract members (with implementation), and so on. Interfaces, on the other hand, contain only abstract member definitions. The polymorphic interface established by an abstract parent class suffers from one major limitation in that only derived types support the members defined by the abstract parent. However, in larger software systems, it is very common to develop multiple class hierarchies that have no common parent beyond System.Object. Given that abstract members in an abstract base class apply only to derived types, we have no way to configure types in different hierarchies to support the same polymorphic interface. By way of example, assume you have defined the following abstract class:

 public abstract class CloneableType { // Only derived types can support this // "polymorphic interface." Classes in other // hierarchies have no access to this abstract // member. public abstract object Clone(); } 

Given this definition, only members that extend CloneableType are able to support the Clone() method. If you create a new set of classes that do not extend this base class, you can't gain this polymorphic interface. Also, you might recall that C# does not support multiple inheritance for classes. Therefore, if you wanted to create a MiniVan that is-a Car and is-a CloneableType, you are unable to do so:

 // Nope! Multiple inheritance is not possible in C# // for classes. public class MiniVan : Car, CloneableType { } 

As you would guess, interface types come to the rescue. After an interface has been defined, it can be implemented by any class or structure, in any hierarchy, within any namespace or any assembly (written in any .NET programming language). As you can see, interfaces are highly polymorphic. Consider the standard .NET interface named ICloneable, defined in the System namespace. This interface defines a single method named Clone():

 public interface ICloneable { object Clone(); } 

Interface : should be used if you want to imply a rule on the components which may or may not be related to each other

优点:

  1. Allows multiple inheritance
  2. Provides abstraction by not exposing what exact kind of object is being used in the context
  3. provides consistency by a specific signature of the contractInterface:
  4. Allows multiple inheritance
  5. Provides abstraction by not exposing what exact kind of object is being used in the context
  6. Provides consistency by a specific signature of the contract

缺点:

  1. Must implement all the contracts defined
  2. Cannot have variables or delegates
  3. Once defined cannot be changed without breaking all the classes

Abstract Class : should be used where you want to have some basic or default behaviour or implementation for components related to each other

优点:

  1. Faster then interface
  2. Has flexibility in the implementation (you can implement it fully or partially)
  3. Can be easily changed without breaking the derived classes

缺点:

  1. Cannot be instantiated
  2. Does not support multiple inheritance

For sure it is important to understand the behaviour of interface and abstract class in OOP (and how languages handle them), but I think it is also important to understand what exactly each term mean. Can you imagine the if command not working exactly as the meaning of the term? Also, actually some languages are reducing even more the differences between interface and abstract… if by chance one day the two terms operate almost identically, at least you can define yourself where (and why) should any of them be used for.

If you read through some dictionaries and other fonts you may find different meanings for a same term but having some common definitions. I think these two meanings I found in this site are really, really good and suitable.

接口:

A thing or circumstance that enables separate and sometimes incompatible elements to coordinate effectively.

抽象:

Something that concentrates in itself the essential qualities of anything more extensive or more general, or of several things; essence.

例:

You bought a car and it needs fuel.

在这里输入图像描述

Your car model is XYZ , so it is a concrete car, a specific instance of a car. A car is not a real object. In fact, it is an abstract set of standards (qualities) to create a specific object. In short, Car is an abstract class , it is "something that concentrates in itself the essential qualities of anything more extensive or more general" .

Only fuel that matches the car manual specification should be used to fill up the car tank. Actually, you can fill up with anything you want but, in fact, the engine will only work properly with the specified fuel, so it is better to follow its requirements. The requirements says that it accepts, as other cars of the same genre ABC , a standard set of fuel.

In an Object Oriented view, fuel for genre ABC should not be declared as a concrete class because there is no real fuel like this out there. Although you could accept an abstract class Fuel or VehicularFuel, you must remember that your car only accept some of the existing vehicular fuel, those that implements the requirements in your car manual. In short, they should implement the interface ABCGenreFuel , which "… enables separate and sometimes incompatible elements to coordinate effectively" .

附录

In addition, I think you should keep in mind the meaning of the term class, which is (from the same site previously mentioned):

类:

A number of persons or things regarded as forming a group by reason of common attributes, characteristics, qualities, or traits; kind;

This way, a class (or abstract class) should not represent only common attributes (like an interface), but some kind of group with common attributes. An interface doesn't need to represent a kind. It must represent common attributes. This way, I think classes and abstract classes may be used to represent things that should not change its aspects often, like a HumanBeing being a Mammal, because it represents some kinds. Kinds should not change themselves that often.

Couple of other differences:

Abstract classes can have static methods, properties, fields etc. and operators, interfaces can't. Cast operator allows casting to/from abstract class but don't allow casting to/from interface.

So pretty much you can use abstract class on its own even if it is never implemented (through its static members) and you can't use interface on its own in any way.

Interface:- == contract.Whichever class implements it has to follow all the specification of interface.

A real-time example would be any ISO marked Product. ISO gives set of rules/specification on how the product should be build and what minimum set of features it Must have.

This is nothing but subset of properties product Must have.ISO will sign the product only if it satisfies the its standards .

Now take a look at this code

 public interface IClock{ //defines a minimum set of specification which a clock should have public abstract Date getTime(); public abstract int getDate(); } public class Fasttrack: Clock { // Must have getTime() and getTime() as it implements IClock // It also can have other set of feature like public void startBackgroundLight() { // watch with internal light in it. } .... //Fastrack can support other feature as well .... .... } 

Here a Fastrack is called as watch because it has all that features that a watch must suppost ( Minimum set of features ).

Why and When Abstract:

From MSDN:

The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class. Abstract simply means if you cannot define it completely declare it as an abstract .Implementing class will complete this implementation.

Eg -: Suppose I declare a Class Recipe as abstract but I dont know which recipe to be made.Then I will generalize this class to define the common definition of any recipe .The implantation of recipe will depend on implementing dish.

Abstract class can consist of abstract methods as well as not abstract method So you can notice the difference in Interface.So not necessarily every method your implementing class must have.You only need to override the abstract methods.

In Simple words If you want tight coupling use Interface o/w use in case of lose coupling Abstract Class