What is an abstract class in C#?
Classes can be defined as user-defined data types representing an object’s state (properties) and behavior (actions).
Types of classes
There are four types of classes in C#, which are as follows:
- Abstract Class
- Partial Class
- Sealed Class
- Static Class
In this Answer, we’ll only discuss the abstract class.
Abstract class
An abstract class is defined as a class that is declared using the abstract keyword and whose object is not created. This type of class provides a standard definition for the subclasses.
To access the object of this class, it must be inherited from another class.
Example
If we run the following code, it will generate an error as we cannot generate an object of the class of type abstract.
abstract class Car{public abstract void startengine();public void enginesound(){System.Console.WriteLine("Broom!");}}class Program{static void Main(string[] args){Car myObj = new Car();}}
Explanation
In the code above:
- Line 1: We generate a class
carof typeabstract. The class type is declared using a specific keyword,abstract. - Lines 2–8: These are the methods specific to the class
Car. - Line 9: This class
Programcontains themainprogram that executes and generates an error signifying that we cannot create an object of the classcar.
We can solve the problem by making a derived class. Try executing the following code. It will not generate any error.
abstract class Car{public abstract void startengine();public void enginesound(){System.Console.WriteLine("Broom!");}}class BMW : Car{public override void startengine(){System.Console.WriteLine("Engine started.");}}class Program{static void Main(string[] args){BMW myBMW = new BMW();myBMW.startengine();myBMW.enginesound();}}
Note: The code above uses C# version 7 or later.
The code above is the same as the previous one, but lines 9–15 contain a derived class BMW. In lines 20–22, we generate an object of class BMW rather than that of car. Therefore, there is no error in the execution of the code.
Free Resources