[. Net Object-Oriented Programming Basics] (16) interface,. net Object-Oriented Programming

Source: Internet
Author: User

[. Net Object-Oriented Programming Basics] (16) interface,. net Object-Oriented Programming

[. Net Object-Oriented Programming Basics] (16) Interface

The term "interface" is similar to the "interface" of the computer hardware we usually see. Taking a computer as an example, we can see its USB interface and COM interface from the outside. The purpose of these interfaces is to make peripherals produced by third-party manufacturers share the same standards, it also provides an external communication or operation portal.

Except for the above features, the C # interface also has a template-like function. We define a set of interfaces, just like a template. This is different from the abstract class. The abstract class first has the concept of a subclass or a subclass, and a class is abstracted from it. The interface is more like we need to design a machine. First, we need to list the external functional interfaces of this machine and then implement them in detail. Of course, this statement is from the perspective of software design.

1. What is an interface?

An interface combines implicit public methods and attributes to encapsulate a set of specific functions.

A simple understanding of interfaces is a convention that ensures that the classes or structures of interfaces are consistent in form.

The interface describes a set of functions that can belong to any class or structure. Therefore, the class or structure that implements the interface must implement the interface members specified in the interface definition.

The interface is defined using the interface keyword. It can be composed of methods, attributes, events, indexers, or any combination of the four member types.

Interface Name, usually starting with I (it is important to name according to specifications)

2. interface features

A. An interface is similar to an abstract base class and cannot be directly instantiated. Methods in an interface are abstract methods. Any non-Abstract type that implements an interface must implement all the members of the interface:

When explicitly implementing this interface, the implemented members cannot be accessed through class instances, but can only be accessed through interface instances.

When the interface is implicitly implemented, the implemented members can be accessed through class instances or interface instances, but the implemented members must be public.

B. The interface cannot contain constants, fields, operators, instance constructors, destructor or types, or static members.

C. The interface members are automatically published and cannot contain any access modifiers.

D. The interface itself can inherit from multiple interfaces. The class and structure can inherit from multiple interfaces, but the interface cannot inherit classes.

3. Differences between interfaces and abstract classes:

Interfaces are used for standardization, and abstract classes are used for commonality.

The interface can only declare methods, attributes, events, and indexers. Abstract classes can be implemented using methods or non-static class variables.

Abstract classes are classes, so they can only be inherited by a single object, but multiple interfaces can be implemented at a time.

Abstract classes can provide partial implementation of some methods, but interfaces cannot.

An example of an abstract class is given by its subclass. An interface instance is provided by the class that implements the interface.

When a method is added to an abstract class, its subclass has this method at the same time. When a new method is added to an interface, the class implementing it must be rewritten (that is why the interface is a Class Specification ).

Interface members are defined as public, however, abstract class members can also be private, protected, internal, or protected internal members (the protected internal members can only be accessed in the application code or derived classes).

In addition, the interface cannot contain fields, constructors, destructor, static members, or constants.

An abstract class can contain the implementation of some Members, but an interface does not contain the implementation of Members. Abstract members of an abstract class can be implemented by the quilt class, and the members of an interface must implement the class completely; A class may inherit an abstract class, but multiple interfaces can be implemented.

4. Similarities and Differences between interfaces and abstract classes in the design perspective

The above describes the differences between interfaces and abstract classes in terms of appearance or form. In addition, interfaces and abstract classes also have many differences in the design process, this is why C # has designed abstract classes and interfaces. That is, they use different occasions.

First, class is the abstraction of objects; abstract class is the abstraction of classes; interface is the abstraction of behavior;

Second, if the behavior spans different classes of objects, you can use interfaces; for some similar objects, use the inherited abstract class;

Third, from the design point of view, the abstract class discovers common things from the subclass, generalize the parent class, and then the subclass inherits the parent class. The interface and the present do not know the existence of the subclass, the implementation of the method is not confirmed, that is, pre-defined.

In actual projects, abstract classes are often produced through refactoring, unless you know in advance that there are many sub-classes to be implemented to abstract classes, that is, bottom-up design. The interface is designed from top to bottom to implement those actions at the beginning of the project design.

5. Sample Code

Through the above learning, we know the differences between abstract classes and interfaces and their use in the design perspective. Next, we re-design our Animal (Animal) and their child Dog, Cat, and Sheep according to international practices) if we know in advance that there is a kind of pleasant goat (PleasantSheep) and a kind of cat BlueCat, they have a common behavior that is to talk. At this time, we will surely think of defining an abstract method for their abstract class Animal to Speak (Speak). Haha, silly, wrong, can all animals Speak? To solve this problem, we need to use interfaces. we know in advance that there is a "speech" behavior, so I will define a speech interface (ISpeak). The UML diagram is as follows:

 

Let's take a look at the code below:

 

1 /// <summary> 2 // animal class (parent class abstract class) 3 /// </summary> 4 abstract class Animal 5 {6 /// <summary> 7 /// name 8 /// description: class and subclass can access 9 /// </summary> 10 protected string name; 11 12 /// <summary> 13 /// constructor 14 /// </summary> 15 /// <param name = "name"> </param> 16 public animal (string name) 17 {18 this. name = name; 19} 20 21 private int shoutNum = 3; 22 public int ShoutNum 23 {24 get {return shoutNum;} 25 Set {shoutNum = value;} 26} 27 28 // <summary> 29 // name (Virtual attribute) 30 /// </summary> 31 public virtual string MyName 32 {33 get {return this. name;} 34} 35 36 // <summary> 37 // call, this method removes the virtual method, write the loop here 38 // </summary> 39 public void Shout () 40 {41 string result = ""; 42 for (int I = 0; I <ShoutNum; I ++) 43 result + = getShoutSound () + "! "; 44 45 Console. writeLine (MyName); 46 Console. writeLine (result); 47} 48 49 // <summary> 50 // create a call imaginary method, subclass rewrite 51 // </summary> 52 // <returns> </returns> 53 public virtual string getShoutSound () 54 {55 return ""; 56} 57} 58 59 // <summary> 60 // declare an interface ISpeak (speech) 61 // </summary> 62 interface ISpeak 63 {64 void Speak (); 65} 66 67 // <summary> 68 // dog (subclass) 69 /// </summary> 70 class Do G: Animal 71 {72 string myName; 73 public Dog (string name): base (name) 74 {75 myName = name; 76} 77 // <summary> 78 // name (override the parent class attribute) 79 // </summary> 80 public override string MyName 81 {82 get {return "I am: dog, my name is:" + this. name;} 83} 84 // <summary> 85 // call (override parent class method) 86 // </summary> 87 public override string getShoutSound () 88 {89 return "Wang! "; 90} 91} 92 93 94 // <summary> 95 // Cat (subclass) 96 /// </summary> 97 class Cat: animal 98 {99 string myName; 100 public Cat (string name): base (name) 101 {102 myName = name; 103} 104 // <summary> 105 // name (override the parent class attribute) 106 /// </summary> 107 public override string MyName108 {109 get {return "I am: cat, my name is:" + this. name;} 110} 111 // <summary> 112 // call (override parent class method) 113 // </summary> 114 public override string getSh OutSound () 115 {116 return "Meow! "; 117} 118} 119 120 // <summary> 121 // Blue Cat (subclass) 122 // inherit Cat and ISpeak123 // </summary> 124 class BlueCat: Cat, ISpeak125 {126 string myName; 127 public BlueCat (string name): base (name) 128 {129 myName = name; 130} 131 // <summary> 132 // name (override parent class attributes) 133 /// </summary> 134 public override string MyName135 {136 get {return "I am: Blue Cat, my name is:" + this. name;} 137} 138 139 // <summary> 140 // Speak14, a member implementing the ISpeak 1 /// </summary> 142 public void Speak () 143 {144 Console. writeLine ("I will talk:" Hello, my name is: "+ this. name + "~~~" "); 145} 146 147 148 149 // <summary> 150 // goat (subclass) 151 // </summary> 152 class Sheep: animal153 {154 string myName; 155 public Sheep (string name): base (name) 156 {157 myName = name; 158} 159 // <summary> 160 // name (override the parent class attribute) 161 /// </summary> 162 public override string MyName163 {164 get {return "I am: Goat, my name is:" + this. name;} 165} 166 // <summary> 167 // call (override parent class method) 168 // </summary> 169 public override strin G getShoutSound () 170 {171 return! "; 172} 173} 174 175 // <summary> 176 // pleasant goat (subclass) 177 // inherit Sheep and interface ISpeak178 /// </summary> 179 class PleasantSheep: Sheep, ISpeak180 {181 string myName; 182 public PleasantSheep (string name): base (name) 183 {184 myName = name; 185} 186 // <summary> 187 // name (override parent class attributes) 188 /// </summary> 189 public override string MyName190 {191 get {return "I am: pleasant goat, my name is:" + this. name;} 192} 193 // <summary> 194 // implementation Interface ISpeak member Speak195 /// </summary> 196 public void Speak () 197 {198 Console. writeLine ("I will talk:" Hello, my name is: "+ this. name + "~~~" "); 199} 200}

Call 1:

// The pleasant goat is now playing Animal pleasantSheep = new PleasantSheep ("the most handsome pleasant goat"); pleasantSheep. shout (); ISpeak IPleasantSheepSpeak = new PleasantSheep ("the most handsome pleasant goat"); IPleasantSheepSpeak. speak (); Console. readLine ();
// The result is as follows: // my name is pleasant goat. My name is the most handsome pleasant goat. // Hey !! Hey !! Hey !! // I will say something: "Hello, my name is: the most handsome pleasant goat ~~~"

Call 2:

// Animal blueCat = new BlueCat ("most beautiful blue cat"); blueCat. shout (); ISpeak IBlueCatSpeak = new PleasantSheep ("the most beautiful blue cat"); IBlueCatSpeak. speak (); Console. readLine ();
// The result is as follows: // I am a Blue Cat. My name is the most beautiful blue cat. // Meow !! Meow !! Meow !! // I will say something: "Hello, my name is: the most beautiful blue cat ~~~"

 

6. Key points:

A. A simple understanding of interfaces is A convention that ensures that the classes or structures of interfaces are consistent in form.

B. The interface class can implement methods, attributes, events, and indexers, and cannot implement delegation. The delegate is a type, but the interface member is not a type.

C. The members in the interface are used to define the contract for communication between objects. it is meaningless to specify the members in the interface as private or protected. They are public by default.

D. interfaces can inherit multiple interfaces, but cannot inherit classes

E. The class can inherit multiple interfaces, but cannot inherit

F. What are the similarities and differences between interfaces and classes:

Differences:

The interface cannot be instantiated directly.

The interface does not contain the implementation of methods.

Interfaces can implement multi-inheritance, while classes can only be single-inheritance.

Class definition can be split between different source files.

Same:

Interfaces, classes, and structures can be inherited from multiple interfaces.

An interface is similar to an abstract base class: any non-Abstract type that inherits an interface must implement all the members of the interface.

Interfaces can contain events, indexers, methods, and attributes.

A class can implement multiple interfaces.

========================================================== ========================================================== ====================

Returned directory

<If it is helpful to you, remember to click on the recommendations. If you do not understand the content or do not write it correctly, please contact us more>
 

========================================================== ========================================================== ====================

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.