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:
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:
/// /// Define an abstract class ///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; } /// /// Implement an abstract class /// 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. abstract classes 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
Remember, one of the most important principles of Object-oriented thinking is interface-oriented programming.
With the help of interfaces and abstract classes, many of the 23 design patterns have been cleverly implemented. I think the essence is simply abstract programming.
Abstract classes are mainly used for closely related objects, and interfaces are most suitable for providing general functions for irrelevant classes.
The interface focuses on the can-do relationship type, while the abstract class focuses on the IS-A relationship;
Behavior of Multi-definition objects in interfaces; Attributes of Multi-definition objects in abstract classes;
Interface definitions 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.
"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.
If possible, the interface design can be a single functional block. Taking. NET Framework as an example, idisposable, idisposable, icomparable, iequatable, and ienumerable all contain only one public method.
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.
All methods in the interface are public by default.
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.
A non-abstract class derived from an abstract class must include all the inherited abstract methods and the actual implementation of the abstract accessors.
Abstract classes cannot use the new keyword or be sealed because they cannot be instantiated.
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:
FCL uses an interface-based design for the Collection class. Therefore, pay attention to the interface design and implementation in system. collections;
FCL uses the 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
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
Public interface iaction { // Define public method labels Void move (); } |
3. Implement abstract classes and interfaces
Public class Duck: Animal, iaction { Public duck (string name) { _ Name = Name; } // Overload the abstract MethodPublic 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
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.
Dunai believes that an abstract class is used to extract the common expression of a specific class, and an interface is used to "combine" 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 you want to create multiple versions of a component, create an abstract class. 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.