Differences between abstract classes and interfaces in C #

Source: Internet
Author: User

Recently, I have been studying the design model. Each model is inherited from previous experiences. It is a general solution for a certain type of problems that has been summarized and formed. These are actually purposeful, I am talking about the importance of interfaces. I think the design model is very important, so its common use is even more important, when I recently learned the design pattern, I always encountered interfaces. abstract classes. This pattern is an abstract class, and that pattern is an interface. I am confused and decided to study it carefully, I would like to share with you the results of my research. I hope you will give more comments.

 

What is an interface?

A protocol used to define a program. The class or structure that implements the interface must be strictly consistent with the interface definition. With this protocol, you can leave the restrictions of programming languages away (theoretically ). C # interfaces can be inherited from multiple basic interfaces, while classes or structures can implement multiple interfaces. The C # interface can contain methods, attributes, events, and indexers. The interface itself does not provide the Implementation of the members it defines. The interface only specifies the class that implements the interface or the members that the interface must provide.

 

How to use interfaces?

For example:

Using system; using system. collections. generic; using system. LINQ; using system. text; namespace uses the abstract mode data access program {class program {static void main (string [] ARGs) {user = new user (); department dept = new Department (); // ifactory factory = new sqlserverfactory (); ifactory factory = new accessfactory (); // The dependency iuser IU = factory has been removed from the access to the specific database. createuser (); IU. insert (User); IU. getuser (1); idepartment ID = Factory. createdepartment (); Id. insert (Dept); Id. getdepartment (1); console. read () ;}} class user {private int ID; Public int ID {get {return ID;} set {id = value ;}} class Department {private int ID; public int ID {get {return ID;} set {id = value ;}}// the idepartment interface is used for client access to remove coupling with specific database access. Interface idepartment {void insert (Department); Department getdepartment (int id);} // sqlserverdepartment class, used to access the Department class sqlserverdepartment of SQL Server: idepartment {public void insert (Department) {console. writeline ("adding a record to the Department table in SQL Server");} public department getdepartment (INT ID) {console. writeline ("obtain a department table record by ID in SQL Server"); return NULL ;}// access class, used to access the Department class accessdepartment: idepartment {public void insert (Department) {console. writeline ("adding a record to the Department table in access");} public department getdepartment (int id) {console. writeline ("obtain a department table record by ID in access"); return NULL ;}// iuser interface for client access, remove the coupling interface iuser {void insert (User user); User getuser (int id);} // sqlserveruser class used to access the SQL Server user class sqlserveruser: iuser {public void insert (User user) {console. writeline ("adding a record to the user table in SQL Server");} public user getuser (INT ID) {console. writeline ("obtain a user table record by ID in SQL Server"); return NULL ;}// access class, used to access the access user class accessuser: iuser {public void insert (User user) {console. writeline ("adding a record to the user table in access");} public user getuser (int id) {console. writeline ("a record in access according to the obtained User table"); return NULL ;}// ifacloud interface, define an abstract factory interface ifacloud {iuser createuser (); // added interface method idepartment createdepartment ();} // sqlserverfactory class, implement the ifactory interface to instantiate sqlserveruser and sqlserverdepartment class sqlserverfactory: ifactory {public iuser createuser () {return New sqlserveruser ();} public idepartment createdepartment () {return New sqlserverdepartment ();}} // accessfactory class, which implements the ifactory interface, instantiates accessuser and accessdepartment class accessfactory: ifacloud {public iuser createuser () {return New accessuser ();} public idepartment createdepartment () {return New accessdepartment ();}}}



What is an abstract class?

An abstract class is a class that contains abstract methods. So what is an abstract method? Abstract methods have no content. There is only one method name and a list of parameters. And ends. In order to mark his uniqueness, add abstract before his return type. Add abstract before the class.

In short, abstract methods and classes are abstract methods and classes.

 

How can I use abstract classes, abstract methods, and abstract methods?


For example:

Using system; using system. collections. generic; using system. LINQ; using system. text; namespace status Mode Structure {class program {static void main (string [] ARGs) {// set the initial state of context to concretestatea context c = new context (New concretestatea (); // continuously requests and updates the status C. request (); C. request (); C. request (); C. request (); console. read () ;}// context class, which maintains an instance of the concretestate subclass. This instance defines the current state class context {private State state; // define the initial state of context public context (State state) {This. state = State;} // read/write status attribute for reading the current state and setting the new State public state {get {return state;} set {state = value; console. writeline ("Current status:" + state. getType (). name) ;}}// process the request and set the next public void request () {state. handle (this) ;}// abstract state class state, define an interface to encapsulate behaviors related to a specific State of context abstract class State {public abstract void handle (context);} // concretestate class, specific state, each subclass implements a behavior class concretestatea: State {public override void handle (context) {// sets the next state of concretestatea to concretestateb context. state = new concretestateb () ;}} class concretestateb: State {public override void handle (context) {// set the next state of concretestateb to concretestatea context. state = new concretestatea ();}}}



Obfuscation of interfaces and abstract classes cannot blame me, because they do have similarities:

Similarities between interfaces and abstract classes:

1. It cannot be instantiated;

2. contains an unimplemented method statement;

3. The derived class must implement unimplemented methods. The abstract class is an abstract method, and the interface is all members (not only the methods include other members );

 

However, they are quite different.


Differences between interfaces and abstract classes:

1. Classes are abstract objects. abstract classes can be interpreted as classes as objects. abstract classes are called abstract classes. interfaces are just a specification or provision of behavior.

2. The interface basically does not have any specific characteristics of inheritance. It only promises the methods that can be called;

3. A class can implement several interfaces at a time, but only one parent class can be extended.

4. interfaces can be used to support callback, but inheritance does not.

5. the abstract class cannot be sealed.

6. The specific methods implemented by abstract classes are virtual by default, but the interface methods in the class implementing interfaces are non-virtual by default. Of course, you can also declare them as virtual.

7. Similar to a non-abstract class, an abstract class must provide its own implementation for all the members of the interface listed in the base class list of this class. However, the abstract class is allowed to map interface methods to abstract methods.

8. abstract classes implement a principle in OOP that separates mutable from immutable. Abstract classes and interfaces are defined as immutable classes, while variable class classes are implemented.

9. A good interface definition should be specific and functional, rather than multi-functional, otherwise it will cause interface pollution. If a class only implements a function of this interface and has to implement other methods in the interface, it is called interface pollution.

10. Avoid using inheritance to implement the build function, but use black box multiplexing, that is, object combination. As the hierarchy of inheritance increases, the most direct consequence is that when you call a class in this group, you must load all of them into the stack! The consequences can be imagined (based on the stack principle ). At the same time, some interested friends can note that Microsoft often uses the object combination method when building a class. For example, in Asp.net, the page class has server request and other attributes, but in fact they are all objects of a certain class. This object of the page class is used to call the methods and attributes of other classes. This is a very basic design principle.

11. If an abstract class implements an interface, you can map the methods in the interface to the abstract class as an abstract method without having to implement it. Instead, you can implement the methods in the subclass of the abstract class.


When to use abstract classes and interfaces

 

1. If you want to create multiple versions of a component, create an abstract class. Abstract classes provide simple methods to control component versions.

2. If the created function is used across a wide range of different objects, the interface is used. If you want to design small and concise functional blocks, use interfaces.

3. If you want to design a large functional unit, use the abstract class. If you want to provide general implemented functions among all the implementations of the component, use the abstract class.

4. abstract classes are mainly used for closely related objects. interfaces are suitable for providing general functions for irrelevant classes.

 

 

The following are a few metaphors that are very relevant. You may also understand a lot of them.


1. Planes fly and birds fly. They all inherit the same interface "fly". However, f22 belongs to the aircraft abstract class and pigeon belongs to the bird abstract class.

2. just like all doors (abstract class), I can't give you a door (I can't instantiate it), but I can give you a specific door or wooden door (polymorphism ); it can only be a door. You cannot say it is a window (single inheritance); a door can have a lock (Interface) or a doorbell (multiple implementations ). A door (abstract class) defines what you are and an interface (LOCK) specifies what you can do (one interface is best to do only one thing, you cannot require a lock to make sound (interface contamination )).

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.