Classes can be defined as user-defined data types representing an object’s state (properties) and behavior (actions).
There are four types of classes in C#, which are as follows:
In this Answer, we’ll only discuss the 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.
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();}}
In the code above:
car
of type abstract
. The class type is declared using a specific keyword, abstract
.Car
.Program
contains the main
program that executes and generates an error signifying that we cannot create an object of the class car
.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