You must know the. NET pair interface and abstract class (zhuan)

Source: Internet
Author: User
Tags define abstract
Document directory
  •  

Author: Anytao Source: Forum Organizing Editor: Ark

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 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

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.

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.