1. Introduction
In my previous post titled "who is the abstract class and interface?", I discussed with my colleague Guan Wei and got the attention of many friends, because it is not a systematic theory, therefore, it is inconvenient for everyone to understand. At the same time, I think it is also necessary to summarize the systemic theory of this topic. Therefore, this article has been released. At the same time, I will also explain the problems mentioned above.
2. introduction of concepts
● What is an interface?
An interface is an abstract type that contains a set of virtual methods. Each method has its name, parameter, and return value. Interface methods cannot contain any implementations. CLR allows interfaces to include events, attributes, indexers, static methods, static fields, static constructors, and constants. Note: C # cannot contain any static members. A class can implement multiple interfaces. When a class inherits an interface, it must not only implement all methods defined by this interface, but also implement all methods inherited from other interfaces.
Definition method:
Reference content is as follows: Public interface System. IComparable { Int CompareTo (object o ); }Public class TestCls: IComparable { Public TestCls () { } Private int _ value; Public int Value { Get {return _ value ;} Set {_ value = value ;} } Public int CompareTo (object o) { // Use the as mode for transformation judgment TestCls aCls = o as TestCls; If (aCls! = Null) { // Implement the abstract Method Return _ value. CompareTo (aCls. _ value ); } } } |
● What is an abstract class?
Abstract classes provide multiple Derived classes that share the public definitions of the base class. They can provide both abstract methods and non-abstract methods. Abstract classes cannot be instantiated. They must be inherited by the derived classes to implement their abstract methods. Therefore, abstract classes cannot use the new keyword or be sealed. If the derived class does not implement all abstract methods, the derived class must also be declared as an abstract class. In addition, the overriding method is used to implement the abstract method.
Definition method:
Reference content is as follows: /// <Summary> /// Define an abstract class /// </Summary> Abstract public class Animal { // Define static Fields Static protected int _ id;// Define attributes Public abstract static int Id { Get; Set; } // Define the Method Public abstract void Eat (); // Define the Indexer Public string this [int I] { Get; Set; } } /// <Summary> /// Implement an abstract class /// </Summary> Public class Dog: Animal { Public static override int Id { Get {return _ id ;} Set {_ id = value ;} } Public override void Eat () { Console. Write ("Dog Eats .") } } |
3. Similarities and Differences
3.1 similarities
● They cannot be directly instantiated. They can all be inherited to implement their abstract methods.
● It is the technical basis for abstract programming and implements many design modes.
3.2 differences
● Interfaces support multi-inheritance; abstract classes cannot implement multi-inheritance.
● An interface can only define abstract rules. An abstract class can either define rules or provide implemented members.
● An interface is a set of behavioral norms; an abstract class is an incomplete class that focuses on the concept of a family.
● Interfaces can be used to support callback. abstract classes cannot implement callback because inheritance is not supported.
● An interface only contains methods, attributes, indexers, and event signatures, but cannot define fields or methods that contain implementations. An abstract class can define fields, attributes, and methods that have implementations.
● The interface can act on the Value Type and reference type; the abstract class can only act on the reference type. For example, Struct can inherit interfaces rather than classes.
Through comparison between the same and different types, we can only talk about interfaces and abstract classes, each of which has its own strengths, but has no advantages. In actual programming practices, we need to take appropriate measures based on actual situations. However, the following experiences and accumulation may give you some inspiration, except for some of my accumulation, many of them come from classic networks. I believe they can withstand the test. So in terms of rules and occasions, the most important thing for us to learn these classics is to apply what we have learned. Of course, I will give my family a wide smile.
3.3 rules and occasions
1. Remember, one of the most important principles of Object-oriented thinking is interface-oriented programming.
2. With the help of interfaces and abstract classes, many ideas in 23 design patterns are cleverly implemented. I think the essence is simply abstract programming.
3. abstract classes should be mainly used for closely related objects, and interfaces are most suitable for providing general functions for irrelevant classes.
4. The interface focuses on the CAN-DO relationship type, while the abstract class focuses on the IS-A relationship;
5. Interface multi-definition object behavior; abstract class multi-definition object attributes;
6. The interface definition can use public, protected, internal, and private modifiers, but almost all interfaces are defined as public, so you don't have to say much about the reason.
7. "interface unchanged" is an important factor to consider. Therefore, when an extension is added by an interface, a new interface should be added instead of an existing interface.
8. Use the. NET Framework as an example. IDisposable, IDisposable, IComparable, IEquatable, and IEnumerable all have only one public method.
9. The upper-case letter "I" before the interface name is an agreement, just as it starts with an underscore below the field name. Stick to these principles.
10. All methods in the interface are public by default.
11. If a version issue is expected, you can create an "abstract class ". For example, if you have created a Dog, a Chicken, and a Duck, you should consider abstracting the Animal to deal with future things. Adding a new member to an interface requires you to modify all the derived classes and re-compile them. Therefore, it is best to use an abstract class to solve the version problem.
12. Non-abstract classes derived from abstract classes must include all the inherited abstract methods and the actual implementation of the abstract accessors.
13. The abstract class cannot use the new keyword or be sealed because the abstract class cannot be instantiated.
14. static or virtual modifiers cannot be used in abstract method declarations.
The above rules are tentatively set to T14. If I am so tired of writing, I will be rewarded for the moment. You can also contact each other. I will revise it in time.
4. Classic example
4.1 Absolute classic
. NET Framework is the best resource for learning. Conscious Research of FCL is a required course for every. NET programmer. I have the following suggestions on the use of interfaces and abstract classes in FCL:
1. FCL uses an interface-based design for the Collection class. Therefore, pay attention to the interface design and implementation in System. Collections;
2. FCL uses Abstract class-based design for Data Stream-related classes. Therefore, pay attention to the abstract class design mechanism of the System. IO. Stream class.
4.2 special dishes
The following example marks the classic as "relative" because of my understanding. As for when to be promoted to "absolute", I am here. is it possible to be so persistent on the path pursued by NET as always, so I will reconstruct the relative structure to the absolute end (haha ). This example does not describe the application of abstract classes and interfaces in the design mode, because it will be another valuable text to be discussed. This article focuses on understanding concepts and principles, but the real application comes from specific requirements and specifications.
Design structure:
1. define abstract classes
Reference content is as follows: Public abstract class Animal { Protected string _ name;// Declare abstract attributes Public abstract string Name { Get; } // Declare the abstract Method Public abstract void Show (); // General Implementation Method Public void MakeVoice () { Console. WriteLine ("All animals can make voice! "); } } |
2. Define Interfaces
Reference content is as follows: Public interface IAction { // Define public method labels Void Move (); } |
3. Implement abstract classes and interfaces
Reference content is as follows: Public class Duck: Animal, IAction { Public Duck (string name) { _ Name = name; }// Overload the abstract Method Public override void Show () { Console. WriteLine (_ name + "is showing for you ."); } // Overload abstract attributes Public override string Name { Get {return _ name ;} } // Interface Implementation Method Public void Move () { Console. WriteLine ("Duck also can swim ."); } } Public class Dog: Animal, IAction { Public Dog (string name) { _ Name = name; } Public override void Show () { Console. WriteLine (_ name + "is showing for you ."); } Public override string Name { Get {return _ name ;} } Public void Move () { Console. WriteLine (_ name + "also can run ."); } } |
4. Client implementation
Reference content is as follows: Public class TestAnmial { Public static void Main (string [] args) { Animal duck = new Duck ("Duck "); Duck. MakeVoice (); Duck. Show (); Animal dog = new Dog ("Dog "); Dog. MakeVoice (); Dog. Show (); IAction dogAction = new Dog ("A big dog "); DogAction. Move (); } } |
5. other mountains and stones
The so-called truth is what we have seen, so we can list innovative ideas in the garden here. One is to thank everyone for sharing, and the other is to improve the words of the family, I hope that I can build knowledge in the field, use it for me, and use it for the public.
● [Url =] dunai [/url]: abstract classes are used to extract the common expression of a specific class, while interfaces are used to generate irrelevant classes into a common group. As for their syntaxes in various languages, language details are not my focus.
● The collection of Hua Shan Jian is also very good.
● Artech believes that Abstract Class should be used whenever possible for code sharing and scalability. Of course, the advantages of interfaces in other aspects cannot be ignored.
● Shenfx believes that interfaces are used when looking for functional commonalities between objects with large differences. When looking for functional differences between objects with large differences, use abstract base classes.
Finally, the MSDN suggestions are as follows:
● If multiple versions of a component are expected to be created, an abstract class is created. Abstract classes provide a simple way to control component versions. By updating the base class, all inheritance classes are automatically updated with the change. On the other hand, the interface cannot be changed once it is created. If you need a new version of the interface, you must create a new interface.
● If the created function is used across a wide range of different objects, the interface is used. Abstract classes are mainly used for closely related objects, and interfaces are most suitable for providing general functions for irrelevant classes.
● If you want to design small and concise functional blocks, use interfaces. If you want to design a large functional unit, use an abstract class.
● If you want to provide common implemented functions among all the implementations of a component, use an abstract class. Abstract classes allow partial implementation classes, while interfaces do not include the implementation of any member.
6. Conclusion
Interfaces and abstract classes are one of the most discussed topics on the Forum and in the classroom. The reason why I discuss this old topic is that from my experience, a deep understanding of these two basic content of object-oriented is crucial to revitalize the abstract programming ideology of object-oriented programming. This article gives a basic overview of the concepts, similarities and use rules of interfaces and abstract classes. From a learning point of view, I think these summaries are sufficient to express their core. However, the deep understanding of object-oriented and software design is based on continuous practice. Scott said that he insisted on writing a Demo every day for an hour. Should we be more diligent in the keyboard. For interfaces and abstract classes, please use them for more information.