I. Concepts of abstract classes and abstract methods
Virtual methods in a base class can sometimes not be called, but simply express an abstract concept that provides a common interface for its derived classes. C # introduces the concept of abstract class, which can be defined as an abstract method. Define the class where the method resides as an abstract class.
Abstract method: Contains only the method definition, but does not have the concrete implementation method, needs its subclass or subclass to implement concretely.
Abstract class: An abstract class is a class that can contain abstract members. Abstract classes can only be used as base classes and cannot be instantiated.
Ii. principles of use of abstract and abstract methods
1 A non-abstract method can exist in an abstract class, and an abstract method must be included in an abstract class.
2 Implement the abstract method with the Override keyword. If the subclass does not implement all the abstract methods in the abstract base class, the subclass must also be defined as an abstract class.
3 The modifier cannot be changed after the abstract method is implemented.
4 abstract classes can be inherited by abstract classes, and the results are still abstract classes.
5 All abstract methods must be implemented in a derived class.
Let's take a look at the abstract class in an example:
[CSharp]View PlainCopy
- <span style="Font-family:microsoft yahei;font-size:18px;" > abstract Class Shapleclass declaration
- {
- abstract public void area (); //abstract method, except that the declaration has no actual implementation, so it ends with a semicolon, and no curly braces after the signature
- public Void Fun () //member function
- {
- Console.WriteLine ("This is a non-abstract method! ");
- }
- }
- class Shap:shapleclass
- {
- public override void area () //All methods derived from an abstract class must implement an abstract method in an abstract class
- {
- Console.WriteLine ("This is an abstract method");
- }
- }</span>
[CSharp]View PlainCopy
- <span style="Font-family:microsoft yahei;font-size:18px;" > class Program
- {
- static void Main (string[] args)
- {
- Shap Circle = new Shap ();
- Circle.fun ();
- Circle.area ();
- }
- }</span>
The results of the operation are as follows:
Abstract classes and abstract methods in C #