C# Abstraction

tutorial and example
tutorial and example

Abstraction is a mechanism by which we can hide the complexities and show only functionalities. C# provides an abstract keyword to declare a class and method as abstract. In C#, Abstraction is achieved by two ways:

  1. By abstract class
  2. By Interface

Abstract class and interface both can have abstract methods which are necessary to achieve abstraction.

  1. Abstract Methods:

A Method which has only declaration and no definition is called Abstract Method. An abstract method can only be declared inside abstract class. It must be overridden else there is no meaning of declaring abstract method.

Syntax:

An abstract method can’t be sealed. We can’t declare it as static. It’s internally a virtual method.

  1. Abstract Class:

Abstract class is the class which can have abstract and non abstract methods inside it. Abstract class is used to define a blueprint of a derived class. It can’t be instantiated. This needs to be derived if you want to use its properties.

We have to give implementation of all the abstract methods of abstract class. If you are deriving an abstract class into your class then you must override all the abstract methods present in that class or declare your class as abstract.

Let’s see an example of Abstract class.

Output

C# abstract class example: having Constructors and methods in abstract class

Output