Abstraction and Abstract Class in C#

 

Abstraction is a major concept of object oriented approach. Abstraction refers to dealing with the required properties or a subset of properties of an object which is required for our purposes i.e, we can filter out or abstract only the concerned properties.

 

Let’s take a real time example to discuss about abstraction. Consider a motor company which manufactures both two wheelers and four wheelers. The company vehicle is an object which will be having a set of properties. We can divide the properties to a set of common properties and different properties. For example Modelnumber, SeriesName, Category, Price, Colour etc will be common for two wheeler as well as four wheeler. A two wheeler has a centre stand and side stand, but a four wheeler doesn’t have any of these. A four-wheeler has wiper which is not a property of two wheeler.

 

Depending on the type of vehicle the properties differs this can be easily implemented using abstraction.

 

Abstract classes are those which have at least one method as abstract i.e. which does not have any implementation. These abstract methods will be overridden in the derived classes.

 

In the below example the motor vehicle class is an abstract class which has an abstract method behaviours().The derived classes two-wheeler and four wheeler can override this method and implement their own behaviours. The public properties of motor vehicle will be available to the derived classes.

 

abstract public class MotorVehicle 

{ 

          public string series; 

          public stringmodelnumber; 

          public double showroomprice; 

          abstract public void behaviours(); 

}

 

public class twowheeler : MotorVehicle 

{ 

            public override void behaviours() 

            { 

                      //Implement properties specific to two wheeler here 

                       throw new NotImplementedException(); 

            } 

}

 

public class fourwheeler : MotorVehicle 

{ 

            public override void behaviours() 

            {  

                      //Implement properties specific to two wheeler here 

                      throw new NotImplementedException(); 

            } 

}