Abstract programming: interfaces and abstract classes

Source: Internet
Author: User
Tags define abstract

1. IntroductionIn 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:

  
  
  1. Public interface system. icomparable
  2. {
  3. Int compareto (object o );
  4. }
  5.  
  6. Public class testcls: icomparable
  7. {
  8. Public testcls ()
  9. {
  10. }
  11.  
  12. Private int _ value;
  13. Public int value
  14. {
  15. Get {return _ value ;}
  16. Set {_ value = value ;}
  17. }
  18.  
  19. Public int compareto (object o)
  20. {
  21.  
  22. // Use the as mode for transformation judgment
  23. Testcls acls = o as testcls;
  24. If (acls! = Null)
  25. {
  26.  
  27. // Implement the abstract Method
  28. Return _ value. compareto (acls. _ value );
  29. }
  30. }
  31. }
  • 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:

  
  
  1. /// <Summary>
  2. /// Define an abstract class
  3. /// </Summary>
  4. Abstract public class animal
  5. {
  6. // Define static Fields
  7. Protected int _ id;
  8.  
  9. // Define attributes
  10. Public abstract int id
  11. {
  12. Get;
  13. Set;
  14. }
  15.  
  16. // Define the Method
  17. Public abstract void eat ();
  18.  
  19. // Define the Indexer
  20. Public string this [int I]
  21. {
  22. Get;
  23. Set;
  24. }
  25. }
  26.  
  27. /// <Summary>
  28. /// Implement an abstract class
  29. /// </Summary>
  30. Public class dog: animal
  31. {
  32. Public override int id
  33. {
  34. Get {return _ id ;}
  35. Set {_ id = value ;}
  36. }
  37.  
  38. Public override void eat ()
  39. {
  40. Console. write ("dog eats .")
  41. }
  42. }
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 dishesThe 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

  
  
  1. Public abstract class animal
  2. {
  3. Protected string _ name;
  4.  
  5. // Declare abstract attributes
  6. Public abstract string name
  7. {
  8. Get;
  9. }
  10.  
  11. // Declare the abstract Method
  12. Public abstract void show ();
  13.  
  14. // General Implementation Method
  15. Public void makevoice ()
  16. {
  17. Console. writeline ("all animals can make voice! ");
  18. }
  19. }
2. Define Interfaces

  
  
  1. Public interface iaction
  2. {
  3. // Define public method labels
  4. Void move ();
  5. }
3. Implement abstract classes and interfaces

  
  
  1. Public class duck: animal, iaction
  2. {
  3. Public duck (string name)
  4. {
  5. _ Name = name;
  6. }
  7.  
  8. // Overload the abstract Method
  9. Public override void show ()
  10. {
  11. Console. writeline (_ name + "is showing for you .");
  12. }
  13.  
  14. // Overload abstract attributes
  15. Public override string name
  16. {
  17. Get {return _ name ;}
  18. }
  19.  
  20. // Interface Implementation Method
  21. Public void move ()
  22. {
  23. Console. writeline ("duck also can swim .");
  24. }
  25.  
  26. }
  27.  
  28. Public class dog: animal, iaction
  29. {
  30. Public dog (string name)
  31. {
  32. _ Name = name;
  33. }
  34.  
  35. Public override void show ()
  36. {
  37. Console. writeline (_ name + "is showing for you .");
  38. }
  39.  
  40. Public override string name
  41. {
  42. Get {return _ name ;}
  43. }
  44.  
  45. Public void move ()
  46. {
  47. Console. writeline (_ name + "also can run .");
  48. }
  49.  
  50. }
4. Client implementation

  
  
  1. public class testanmial
  2.     {
  3.         public static void main(string [] args)
  4.         {
  5.             animal duck = new duck("duck");
  6.             duck.makevoice();
  7.             duck.show();
  8.  
  9.             animal dog = new dog("dog");
  10.             dog.makevoice();
  11.             dog.show();
  12.  
  13.             iaction dogaction = new dog("a big dog");
  14.             dogaction.move();
  15.         }
  16.     }

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.