What is an abstract class?
Abstract class is an Object Oriented programming based concept. In simple words, abstract means a non-physical thought, idea, or concept. An abstract class acts as only a base class, which means an abstract class is incomplete. An abstract class is complete with derived class or other child class.
Object oriented programming concept - what is an encapsulation
Purpose of an abstract class
Here, we have different types of cars and trucks. All vehicles have different colors, design and engine types which make them different from each other but they have something in common as all of them have engines, tiers, gears, steering etc. and are used for traveling.
What should be an abstract concept? Vehicle
As shown in the figure given above, vehicle can be a general concept for car and truck. A vehicle provides general information related to car and truck.
Abstract class declaration:
An abstract class is created using “ABSTRACT” keyword before class name.
Example
Abstract class can include both abstract and non-abstract members.
Example
Now, we can create one derived class car to implement abstract method but when we implement an abstract method in derived class, use override keyword before Method name, as shown below.
Now we can create an object in main class but keep in mind, we cannot create an object directly for an abstract class. When any ’abstract class’ is inherited by any other class, we create the objects of that derived class.
Output
Example code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace OPPs
- {
- abstract class Truck
- {
-
- public void Color()
- {
- Console.WriteLine("Base Class : Vehicle Color");
- }
-
- public abstract void Model();
- }
- class Car : Truck
- {
- public override void Model()
- {
- Console.WriteLine("Derived : Vehicle Type Sedan car ");
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Car objCar = new Car();
- objCar.Color();
- objCar.Model();
- Console.ReadLine();
- }
- }
- }
An abstract class is a class, which is used for sharing common functionality to all its derived classes and with the help of an abstract class, it is very easy to change all the related methods into the derived class that can be inherited from the base class without disturbing all other derived classes. In simple words, for code reusability or to avoid code duplication, it is used.
Key Points
- An abstract class cannot be instantiated.
- An abstract method can only be declared in an abstract class.
- All derived classes must implement all the abstract methods in it.
- We cannot create object of abstract class.
- We cannot use sealed modifier.
- An abstract method is by default; a virtual.
- An abstract class is designed to act as a base class.
- Avoid code duplication.
I discussed why an abstract class is important in an Object Oriented programming language.
Have a nice day.