SoFunction
Updated on 2025-03-07

Detailed explanation of the difference between abstract classes and interfaces in C#

1. What is the relationship between interface-oriented programming and object-oriented programming

First of all, interface-oriented programming and object-oriented programming are not horizontal. It is not a programming idea that is more advanced than object-oriented programming, but is attached to the object-oriented thinking system and belongs to it. In other words, it is one of the essence of thought in object-oriented programming systems.

2. The nature of the interface

An interface is an ostensibly composed of several method definitions without body code. It has a unique name and can be implemented by a class or other interface (or can also be said to be inherited). It might look like the following in form:

interface InterfaceName
{
 void Method1();
 void Method2(int para1);
 void Method3(string para2,string para3);
}

So, what is the essence of an interface? Or what is the meaning of the existence of an interface? I think it can be considered from the following two perspectives:

1) An interface is a set of rules that specify a set of rules that a class or interface that implements this interface must have. It embodies the concept of nature that "if you are... you must be able..."

For example, in nature, people can eat, that is, "if you are a human, you must be able to eat." Then when simulated in a computer program, there should be an IPerson (customically, the interface name starts with "I") interface, and there is a method called Eat(). Then we stipulate that every class representing "human" must implement the IPerson interface, which simulates the natural rule of "if you are a human, you must be able to eat".

From here, I think you can also see some object-oriented ideas. One of the cores of object-oriented thinking is to simulate the real world and abstract things in the real world into categories. The entire program relies on instances of various types to communicate with each other and cooperate with each other to complete the system functions. This is very consistent with the operating conditions of the real world and is also the essence of object-oriented thinking.

2) Interfaces are abstract representations of similar things on a certain granular view. Note that here I emphasize on a certain granular view, because the concept of "same thing" is relative, and it varies due to different granular views.

For example, in my eyes, I am a person, and there is a fundamental difference between me and a pig. I can accept the statement that my classmates and I are the same, but I must not accept that I am the same type as a pig. However, if a zoologist's eyes are like pigs, I should be the same, because we are both animals, he can think that both "human" and "pig" have implemented the IAnimal interface. When he studies animal behavior, he will not treat me and pigs separately, but will study it from the larger particle size of "animal", but he will think that there is an essential difference between me and a tree.

Now that I have changed to a geneticist, the situation is different. Because all living things can be inherited, in his eyes, I am not only no different from pigs, but also from a mosquito, a bacteria, a tree, a mushroom, or even a SARS virus, because he would think that we have all realized the IDescendable interface (Note: descend vi. inheritance), that is, we are all hereditable things. He will not study us separately, but will study all living things as similar types. In his eyes, there is no difference between humans and viruses, only hereditable substances and non-heritable substances. But at least, there is still a difference between me and a stone.

Maybe you will think that my example above is nonsense, but this is exactly the meaning of the existence of the interface. One of the object-oriented ideas and core is polymorphism. What is polymorphism? To put it bluntly, it is to treat similar things indiscriminately at a certain granular view level and handle them uniformly. And the reason why I dare to do this is because of the existence of an interface. Like that geneticist, he understood that all organisms have implemented the IDescendable interface. As long as they are organisms, there must be the Descend() method, so he can study them in a unified manner without studying each organism separately and eventually exhausting.

Maybe we can't give you an intuitive impression of the nature and function of the interface. Then in the following examples and the analysis of several design patterns, you will experience the connotation of the interface more intuitively.

3. Interface-oriented programming summary

So what is interface-oriented programming? My personal definition is:In system analysis and architecture, the hierarchy and dependencies are distinguished. Each level does not directly provide services to its upper layer (that is, not directly instantiated in the upper layer), but instead defines a set of interfaces, only exposing its interface functions to the upper layer. The upper layer only depends on the lower layer, and does not rely on specific classes.

The benefits of doing this are obvious, and first of all, it is very beneficial to system flexibility. When the lower layer needs to be changed, as long as the interface and interface functions remain unchanged, the upper layer does not need to make any modifications. You can even replace the lower layer without changing the upper layer code, just like we replace a WD 60G hard drive with a Seagate 160G hard drive. There is no need to make any changes in other parts of the computer, but just unplug the original hard drive and plug in the new hard drive, because the other parts of the computer do not rely on the specific hard drive, but only rely on an IDE interface. As long as the hard drive implements this interface, it can be replaced. From here, the interface in the program is very similar to the interface in reality, so I have always believed that the word interface is really similar!

Another advantage of using interfaces is that developers of different components or levels can start construction in parallel, just like those who build hard disks do not need to wait for CPUs or monitors. As long as the interfaces are consistent and the design is reasonable, development can be carried out in parallel, thereby improving efficiency.

Supplement to this article:

1. Regarding the two words "interface" in "interface oriented programming" and the specific object-oriented language "interface"

I saw a friend suggesting that the word "interface" in "interface oriented programming" should have a larger range than the interface in a simple programming language. After thinking about it, I thought it made sense. What I wrote here is indeed unreasonable. I think "interface" in object-oriented language refers to a specific code structure, such as an interface defined in C# with the interface keyword. The "interface" in "interface-oriented programming" can be said to be a structural component that refers to a more abstract level from the perspective of software architecture and from a more abstract level. In this sense, if an abstract class is defined and the purpose is to achieve polymorphism, then I think it is reasonable to call this abstract class also "interface". But is it reasonable to use abstract classes to implement polymorphism? Discuss in the second article below.

In summary, I think the concepts of two "interfaces" are both different and related to each other. Interfaces in "Interface-oriented programming" are architectural components at the ideological level for realizing polymorphism, improving software flexibility and maintainability, while "interfaces" in specific languages ​​are the means to implement components in this idea into code.

2. About abstract classes and interfaces

If we look at the specific code alone, these two concepts are easy to be blurred, and we even think that the interface is redundant, because from the specific function alone, except for multiple inheritance (in C#, in Java), abstract classes seem to be able to completely replace interfaces. However, is the existence of interfaces to achieve multiple inheritance? Of course not. I think the difference between abstract classes and interfaces is the motivation to use. The use of abstract classes is for code reuse, while the motivation for using interfaces is for polymorphism. So, if you're hesitating about whether to use an interface or an abstract class somewhere, then you can think about what your motivation is.

Seeing a friend’s doubts about the IPerson interface, my personal understanding is that whether the IPerson interface should be defined depends on the specific application. If there are Women and Man in our project, both inherit Person, and most of the methods of Women and Man are the same, and there is only one method, DoSomethingInWC() is different (the example is vulgar, please forgive me), then of course, it is more reasonable to define an AbstractPerson abstract class, because it can include all other methods, and the subclass only defines DoSomethingInWC(), which greatly reduces the amount of duplicate code.

However, if the Women and Man classes in our program basically have no common code, and there is a PersonHandle class that needs to instantiate them, and do not want to know whether they are men or women, but just treat them as humans and implement polymorphism, then it is necessary to define them as interfaces.

In short, the difference between an interface and an abstract class is mainly due to the motivation for use, not itself. When a thing should be defined as an abstract class or an interface, it must be determined based on the context of the specific environment.

Furthermore, I think another difference between an interface and an abstract class is that there should be a general and special relationship between an abstract class and its subclass, while an interface is just a set of rules that its subclass should implement. (Of course, there may be a general and special relationship, but the purpose of our use of interfaces is not here.) For example, it is acceptable to define vehicles as abstract classes, and cars, aircraft, and ships as subclasses, because cars, aircraft, and ships are all special vehicles. For example, the Icomparable interface just says that the classes that implement this interface must be able to be compared, which is a rule. If the Car class implements Icomparable, it just means that there is a way in our Car to compare two Car instances, which may be more expensive than which car or larger than which car. It doesn't matter, but we can't say that "cars are special and can be compared", which is not grammatically applicable.

What is the difference between abstract classes and interfaces in C#.NET?

The concepts of interfaces and abstract classes are different.Interfaces are abstractions of actions, and abstract classes are abstractions of roots.

An abstract class represents what this object is. The interface represents what this object can do.For example, men and women, these two classes (if they are classes...), their abstract class is human. It means that they are all human.

People can eat, and dogs can eat, you can define "eat" as an interface and let these classes implement it.

Therefore, in a high-level language, a class can only inherit one class (abstract class) (just as humans cannot be both biological and non-biological), but can implement multiple interfaces (eating interface, walking interface).

Let’s talk about the differences in applications of the two:

Interfaces play more roles in system architecture design methods, mainly used to define communication contracts between modules.

Abstract classes play a role in code implementation and can realize code reuse

Template method design pattern is a typical application of abstract classes

1 Answer

1Abstract Class

(1) Abstract methods are only declared and do not include implementations. They can be regarded as virtual methods without implementation bodies.

(2) Abstract classes cannot be instantiated

(3) Abstract classes can but do not have abstract properties and abstract methods, but once they have abstract methods, they must declare this class as an abstract class.

(4) The abstract method of the base class must be covered by the specific derived class

(5) Abstract derived classes can overwrite abstract methods of base classes or not. If not overridden, their specific derived classes must override them. like:

using System;
public abstract class A //Abstract Class A{ 
 private int num=0;
 public int Num //Abstract class contains attributes { 
  get 
  { 
   return num; 
  } 
  set 
  { 
   num = value; 
  }   
 }
 public virtual int getNum() //Abstract class contains virtual methods { 
  return num; 
 }
 public void setNum(int n) // //Abstract class contains ordinary methods { 
   = n; 
 }
 public abstract void E(); //Abstract method E in class A}
public abstract class B : A // Since class B inherits the abstract method E in class A, class B also becomes an abstract class{
}
public class C : B 
{ 
 public override void E() //Rewrite abstract methods inherited from class A.  If class B itself defines abstract methods, it must also be rewritten { 
  //throw new Exception("The method or operation is not implemented."); 
 } 
}
public class Test 
{ 
 static void Main() 
 { 
  C c = new C(); 
  (); 
 } 
}

2. Interface

(1) The interface cannot be instantiated

(2) The interface can only contain method declarations

(3) The members of the interface include methods, properties, indexers, and events

(4) The interface cannot contain constants, fields (domains), constructors, destructors, and static members. like:

public delegate void EventHandler(object sender, Event e);
public interface ITest 
{ 
 //int x = 0;
 int A 
 { 
  get; 
  set; 
 }
 void Test();
 event EventHandler Event; 
 int this[int index] 
 { 
  get;
  set; 
 } 
}

(5) All members in the interface are public by default, so there cannot be a private modifier in the interface.

(6) Derived classes must implement all members of the interface

(7) A class can directly implement multiple interfaces, separated by commas

(8) An interface can have multiple parent interfaces, and the class implementing this interface must implement all members of all parent interfaces.

III. Abstract classes and interfaces

Similarities:

(1) All can be inherited

(2) None of them can be instantiated

(3) Both can include method declarations

(4) The derived class must implement unimplemented methods

the difference:

(1) Abstract base classes can define fields, properties, and methods implementations. An interface can only define attributes, indexers, events, and method declarations and cannot contain fields.

(2) An abstract class is an incomplete class that needs further refinement, while an interface is a behavioral norm. Microsoft's custom interface always comes with a field afterwards, proving that it is a type of expression "I can do it...

(3) Interfaces can be implemented multiple times, abstract classes can only be inherited by a single

(4) Abstract classes are more defined between a series of closely related classes, while most interfaces are in classes with loose relationships but all implement a certain function.

(5) Abstract classes are concepts abstracted from a series of related objects, so they reflect the internal commonality of things; interfaces are a functional convention defined to satisfy external calls, so they reflect the external characteristics of things

(6) The interface basically does not have any specific features of inheritance, it only promises methods that can be called

(7) Interfaces can be used to support callbacks, but inheritance does not have this feature

(8) The specific methods implemented by abstract class are default to virtual, but the interface methods in the class that implements interfaces are default to non-virtual. Of course, you can also declare them as virtual.

(9) If an abstract class implements an interface, the methods in the interface can be mapped into the abstract class as an abstract method without having to be implemented, and methods in the interface can be implemented in the subclass of the abstract class.

The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!