C#. What is the difference between an abstract class and an interface in net

Source: Internet
Author: User

First, interface-oriented programming and object-oriented programming are not lateral, it is not an independent programming idea that is more advanced than object-oriented programming, but is attached to the object-oriented ideology, which belongs to its part. Or, it is one of the essence of thought in object-oriented programming system.

2. The nature of the interface

An interface, on the surface, consists of a collection of several method definitions without the principal code, with a unique name that can be implemented by a class or other interface (or, optionally, inherited). It may look like this in form:

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

So what is the nature of the interface? Or what the meaning of the interface exists. I think it can be considered from the following two points of view:

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. Embodies the nature "if you are ... You must be able to ... "the idea.

For example, in nature, people can eat, that is, "If you are human, you must be able to eat". So the simulation to the computer program, there should be a IPerson (the custom interface name from the "I") interface, and there is a method called Eat (), and then we stipulate that each class that represents "human", must implement the IPerson interface, which simulates the nature "If you are human, you must be able to eat" This rule.

From here, I think you can see a little bit of object-oriented thinking. One of the core of object-oriented thinking is to simulate the real world and abstract the real world into classes, and the whole program relies on each kind of instance to communicate with each other and to cooperate with each other to complete the system function, which is very accord with the real world running condition and the essence of object oriented thought.

2) The interface is an abstract representation of the same thing on a certain granularity view. Note here I emphasize that in a certain granularity view, because the concept of "homogeneous thing" is relative, it differs because of the granularity view.

For example, in my eyes, I am a person, and a pig there is an essential difference, I can accept my classmates and I are similar this statement, but can not accept me and a pig is the same. However, if in the eyes of a zoologist, I and pig should be the same, because we are animals, he can think that "man" and "pig" have achieved ianimal this interface, and he in the study of animal behavior, I and pig will not be treated separately, but from the "animal" This larger grain size study, But he would think I was fundamentally different from a tree.

Now for a geneticist, the situation is different, because the living things can be inherited, so in his eyes, I not only with the pig no difference, and a mosquito, a bacterium, a tree, a mushroom and even a SARS virus no difference, because he will think we have achieved the ID Escendable This interface (note: Descend VI. Heredity), that is, we are all heritable things, he will not study us separately, but will all creatures as the same kind of research, in his eyes there is no human and virus, only the genetic material and non-hereditary material. But at least, I have a difference with a stone.

But the unfortunate thing happened, one day, on the earth appeared a great man, his name is Lenin, he is familiar with Marx, Engels of dialectical materialism thought after the masterpiece, quite experience, so he made a famous definition: the so-called material, is to be reflected in the consciousness of the objective reality. At this point, I and a stone, a trace of air, an idiom and transmission of mobile phone signal electromagnetic field has no difference, because in Lenin's eyes, we are can be reflected in the consciousness of the objective reality. If Lenin was a programmer, he would say: the so-called material, is all of the "Ireflectabe" and "IESSE" Two interface class generated by the instance. (Note: Reflect v. reflect esse N. objective reality)

You might think that my example above is a nonsense, but that's what the interface is all about. Object-oriented thinking and one of the core is called polymorphism, what is polymorphism? To put it bluntly is to treat the same things indiscriminately at a certain granularity view level. And the reason to do this is because there is an interface exists. Like the geneticist, he knew that all living creatures realized the IDescendable interface, so long as the creature, there must be descend () This method, so he can be unified research, and not to study each kind of biological and eventually exhausted.

Maybe I can't give you a visual impression of the nature and function of the interface. Then in the following example and in the analysis of several design patterns, you will be more intuitive to experience the connotation of the interface.

3. Overview of interface-oriented programming

So what is interface-oriented programming? My personal definition is: in the system analysis and architecture, distinguish between hierarchy and dependency, each level is not directly to its upper layer to provide services (that is, not directly instantiated in the upper layer), but by defining a set of interfaces, only to the upper layer exposes its interface function, the upper layer for the lower layer is only the interface dependency, not the specific class.

The benefits of doing so are obvious, and first of all, a great benefit to system flexibility. When the lower layer needs to change, as long as the interface and interface functions are not changed, the upper layer does not have to make any changes. You can even replace the entire lower layer without altering the upper code, as if we were replacing a WD 60G hard drive with a Seagate 160G hard drive, instead of having to make any changes in the other parts of the computer, we could unplug the original hard drive and plug it into the new hard drive, because the rest of the computer is not dependent on the hard drive. Instead of relying on an IDE interface, you can replace the hard drive by implementing the interface. From this point of view, the interface in the program is very similar to the interface in reality, so I always think that the word interface (interface) is really in the likeness!

Another advantage of using the interface is that different parts or levels of developers can work in parallel, like making a hard disk without the CPU, and do not wait for the display, as long as the interface is consistent, reasonable design, can be developed in parallel, thereby improving efficiency.

Supplement to this article:

1. About "interface" in "interface-oriented programming" and "interfaces" in specific object-oriented languages two words

See a friend that "interface-oriented programming" in the word "interfaces" should be more than the interface in the simple programming language range. I think it makes sense. I did not write that very well here. I think "interface" in an 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 described as a kind of structural part that hides concrete underlying classes and implements polymorphism 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 refer to this abstract class as an "interface". But is it unreasonable to use abstract class to realize polymorphism? Discussed in the second article below.

To summarize, I think that the concept of two "interfaces" is both different and interrelated. The interface in "interface-oriented programming" is an architectural component of the thought-level for polymorphism, software flexibility, and maintainability, and the "interface" in a specific language is the means by which the parts of the idea are implemented into code.

2. About abstract classes and interfaces

If single from the specific Code view, the two concepts are easy to blur, and even feel that the interface is redundant, because single from the specific function, in addition to multiple inheritance (C#,java), abstract class seems to completely replace the interface. However, does the presence of an interface exist to achieve multiple inheritance? Of course not. I think the difference between abstract classes and interfaces is the use of motivation . abstract classes are used for reuse of code, and the motivation for using interfaces is to achieve polymorphism . So, if you're hesitant about using interfaces or abstract classes somewhere, think about what your motives are.

See a friend to IPerson this interface query, my personal understanding is, IPerson this interface should not be defined, the key to see the specific application is how a situation. If our project has women and man, all inherit person, and women and man most methods are the same, only one method DOSOMETHINGINWC () different (the example is vulgar, you forgive me), Then of course it is reasonable to define a Abstractperson abstract class, because it can include all other methods, the subclass only defines DOSOMETHINGINWC (), and greatly reduces the amount of duplicated code.

However, if the women and man two classes in our program basically do not have common code, and there is a personhandle class that needs to instantiate them and do not want to know that they are male or female, and simply treat them as human beings and realize polymorphism, then it is necessary to define interfaces.

All in all, the difference between an interface and an abstract class lies primarily in the motivation used, not in itself. And whether a thing should be defined as an abstract class or an interface depends on the context of the specific environment.

Furthermore, I think another difference between an interface and an abstract class is that the abstract class and its subclasses should be a general and special relationship, and the interface is just a set of rules that its subclasses should implement. (Of course, sometimes there may be general and special relationship, but we use the purpose of the interface is not here) For example, transportation is defined as abstract class, cars, airplanes, ships defined as sub-categories, is acceptable, because cars, airplanes, ships are a special means of transport. Another example is the IComparable interface, which simply says that the class that implements this interface must be able to be compared, which is a rule. If the car class implements the IComparable, just saying that there is a way in our car to compare two car instances, which may be more expensive than which car, or bigger than which, it does not matter, but we can not say that "the car is a special can be compared", which is not in the grammar.

C#. What is the difference between an abstract class and an interface in net?

The concepts of interfaces and abstract classes are different. An interface is an abstraction of an action, and an abstract class is an abstraction of the root.

The abstract class represents what this object is. The interface represents what this object can do . For example, men, women, these two classes (if it's a class ...) ), their abstract class is human. Description, they are all human.

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

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

The following is the difference between the two applications : The interface is more in the system architecture design method to play a role, mainly used to define the communication contract between the modules. Abstract classes play a role in code implementation and can be reused for code  

Template method Design pattern is a typical application of abstract class

Best Answer:1 abstract class (1) abstract methods are declared only, not implementations, and can be seen as virtual methods without implementations (2) Abstract classes cannot be instantiated (3) abstract classes can but do not have to have abstract properties and abstract methods, but once you have an abstract method, you must declare the class as an abstract class ( 4) The specific derived class must override the base class's abstract method (5) The abstract derived class can override the base class's abstract method or not overwrite it. If they are not overwritten, their specific derived classes must overwrite them. Such as:
Using System;     public abstract Class A//abstract classes a {private int num=0;          public int Num//abstract class contains property {get {return Num;          } set {num = value; }              }
public virtual int Getnum ()//abstract class contains the virtual method {return num; }
public void Setnum (int n)/////abstract class contains the normal method {this.num = n; }
public abstract void E (); Abstract method E} in Class A
Public abstract class B:A//Because Class B inherits the abstract method E from class A, Class B also becomes abstract class {} public class C:b {public override void E () Overrides an abstract method inherited from Class A.      If Class B itself also defines an abstract method, you must also override {//throw new Exception ("The method or operation is not implemented."); }  }
public class Test {static void Main () {c c = new C ();      C.E (); }  }
Second, interface     (1) interface cannot be instantiated     (2) The interface can contain only method declarations     (3) The members of the interface include methods, properties, indexers, events      (4) The interface cannot contain constants, fields (domains), constructors, destructors, static members. such as: public delegate void EventHandler (object sender, Event e); public interface itest  {     //int x = 0;     int a      {&N Bsp         get;          set;      }     void Test ();     event EventHandler event;         int this[int index]      {          get;          set;     } }     (5) All members in the interface default to public, so the interface cannot have the private modifier      (6) Derived classes must implement all members of an interface     (7) A class can implement multiple interfaces directly, with commas separating the interfaces     (8) An interface can have multiple parent interfaces. The class that implements the interface must implement all the members of all the parent interfaces
Abstract classes and interfaces are the same point: (1) can be inherited (2) cannot be instantiated (3) can contain method declarations (4) derived classes must implement the method differences that are not implemented: (1) Abstract base classes can define fields, properties, methods Realize.     An interface can only define properties, 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 code of conduct. Microsoft's custom interface is always behind the able field, proving that it is stating a class of "I can do ... "(3) The interface can be multiple implementations, the abstract class can only be inherited by a single (4) abstract class is more defined in a series of closely related classes, and the interface is mostly loose but the implementation of a function of the class (5) abstract class is from a series of related objects abstracted from the concept, so the reflection of things Internal commonality; An interface is a functional contract defined to satisfy an external invocation, so it reflects the external nature of the thing (6) The interface basically does not have any specific characteristics of inheritance, it only promises to invoke the method (7) interface can be used to support callbacks, and inheritance does not have this feature ( 8) The specific method of the implementation of the abstract class defaults to virtual, but the implementation of the interface of the class interface method is not virtual, of course, you can also declare as virtual (9) If the abstract class implements the interface, you can map the interface method into an abstract class as an abstract method without implementation, and in the subclass of the abstract class Implement interface method

C#. What is the difference between an abstract class and an interface in net

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.