The difference between abstract and virtual methods in C

  • 2020-08-22 22:37:58
  • OfStack

Those of you who have studied C# should know the difference between abstract and virtual methods, and many beginners don't know the difference between the two. Today this article will analyze the difference between 1 and 2. Examples are attached to illustrate. The specific analysis is as follows:

1. Main Differences:

For abstract methods, subclasses must implement it.

Subclasses may or may not override virtual methods.

Therefore, the two constraints are different

2. Example code is as follows:


/*  The statement 1 An abstract class 
* 1. An abstract class can contain variables 
* 2. The body of a method cannot be declared in an abstract method 
*/
abstract class AbsClass
{  
  string name;
  public abstract void DisplayValue(string value);
}

/* A subclass that inherits an abstract class must implement an abstract method */
class AbsClassInherited : AbsClass
{
  /* use override Rewrite the implementation */
  public override void DisplayValue(string value)
  {
    Console.WriteLine(value.ToUpper());
  }
}
 /*  Declare virtual functions 
 */
class VirtClass
{
  /* The statement 1 A virtual function 
    A virtual function must implement the method body */
  public virtual void DisplayValue(string value)
  {
    Console.WriteLine(value);
  }
}
/* Virtual methods may or may not be implemented */
class VirtClassInherited : VirtClass
{
  /* use override Rewrite the implementation */
  public override void DisplayValue(string value)
  {
    Console.WriteLine(value.ToUpper());
  }
}

/*  The statement 1 An interface 
 * 1. Methods in an interface must be public 
 * 2. No variables are allowed in the interface 
 * 3. Methods in an interface are not allowed to have method bodies 
 */
interface IAbs
{
  void DisplayValue(string value);
}

Hopefully, the analysis in this article will help you with your C# programming.


Related articles: