抽象类和接口有什么区别?

抽象类和接口有什么区别?

问题描述:

假设我们在一个接口中有两个方法 M1()M2().抽象类也有相同的两个抽象方法.如果任何类实现了这个接口或继承了抽象类,它就必须实现其中的两个方法.

Suppose we have two methods M1() and M2() in an interface. An abstract class also has just the same two abstract methods. If any class implemented this interface or inherited from the abstract class, it will have to implement both the methods in it.

所以对我来说,接口或抽象类在我的场景中的行为似乎是一样的.那么,任何人都可以在在这种特定情况下强调这两者之间的区别,并建议在这里使用抽象类还是接口?

So to me, it seems that an interface or an abstract class behaves the same for my scenario. So, can anyone highlight the difference between these two in this specific case and suggest whether to use an abstract class or an interface here?

抽象类和接口之间存在技术差异,抽象类可以包含方法、字段、构造函数等的实现,而接口仅包含方法和属性原型.一个类可以实现多个接口,但只能继承一个类(抽象的或其他的).

There are technical differences between Abstract Classes and Interfaces, that being an Abstract Class can contain implementation of methods, fields, constructors, etc, while an Interface only contains method and property prototypes. A class can implement multiple interfaces, but it can only inherit one class (abstract or otherwise).

但是,在我看来,接口和抽象类之间最重要的区别是语义上的区别.

However, in my opinion, the most important difference between Interfaces and Abstract Classes is the semantic difference.

一个接口定义了可以做什么(它的行为方式),一个抽象类定义了一个东西是什么.

An Interface defines what something can do (how it behaves), and an Abstract Class defines what something is.

IEnumerable为例,这背后的语义是任何实现IEnumerable的东西都是可枚举的,并不是说它是一个枚举,而是它可以表现得像一个(可以列举).

Take for example IEnumerable, the semantic meaning behind this is that anything that implements IEnumerable is enumerable, it doesn't mean that it's an enumeration, but that it can behave like one (can be enumerated).

与洗衣机的例子相比,任何继承它的东西都是一种洗衣机.任何继承它的东西都将是一种洗衣机、顶部装载机或侧装载机等.

Contrast that with a washing machine example, anything that inherits it is a type of washing machine. Anything that inherits it would be a type of washing machine, a top loader, or side loader, etc.

相反,如果您有一个名为 ICanWash 的接口,它可以包含一个名为 Wash 的方法.你可以有各种实现ICanWash的东西,比如Person,一个抽象的洗衣机类等等,实际的实现并不重要,你只需要知道行为是它可以洗东西.

Instead, if you had an interface called ICanWash, which could contain a method called Wash. You could have various things implement ICanWash, be it a Person, an abstract washing machine class, etc, where the actual implementation does not matter, just you need to know that the behavior is that it can wash things.

总而言之,类定义什么是什么,接口定义什么可以做什么.

In summary, classes define what something is, interfaces define what something can do.