What is the usage of the abstract keyword in C#?

In C#, the abstract keyword is used to define abstract classes and methods.

  1. Abstract Class:
    An abstract class is a special type of class that cannot be instantiated, only inherited. It can contain abstract methods and non-abstract methods. Abstract methods are defined by adding the “abstract” keyword before the method, having only method signatures without implementation, which is carried out by subclasses that inherit from the abstract class.

Here is an example of defining an abstract class:

abstract class Animal
{
    public abstract void Sound(); // 抽象方法
    public void Sleep() // 非抽象方法
    {
        Console.WriteLine("Animal is sleeping.");
    }
}
  1. Abstract method is a method that only has a method declaration, without a method body, without actual implementation. Abstract methods must be declared in an abstract class. Abstract methods are used to define behaviors in the base class, and the specific implementation is completed by the subclass that inherits the abstract class.

Here is an example of defining an abstract method:

abstract class Animal
{
    public abstract void Sound(); // 抽象方法
}

Subclasses inheriting from an abstract class must implement abstract methods, or else it will result in a compilation error.

Here is an example of inheriting an abstract class and implementing abstract methods.

class Dog : Animal
{
    public override void Sound()
    {
        Console.WriteLine("The dog is barking.");
    }
}

Please note:

  1. Abstract classes cannot be instantiated, they can only be inherited.
  2. Abstract methods can only exist in abstract classes.
  3. Subclasses inheriting from an abstract class must implement abstract methods.
  4. If a class inherits an abstract class but does not implement all the abstract methods, then the class must also be defined as an abstract class.
bannerAds