Abstract Class in C#

Posted by Simplify DotNet on December 26, 2020 in , , , | No comments

 Abstract Class 


    We can not create an object of an abstract class in C#, so we need to inherit the abstract class using another normal class and then we can use the methods and data members present in the abstract class.
In the abstract classes we should not provide the whole implementation of logic but we should only have the outline of the class and then we can inherit the class to provide the full implementation of the class.
    Abstract classes are declared using abstract keyword as shown below.

    public abstract class Vehicle
   {

    }


    If we need to take a real time example of the abstract class then we can imagine an abstract class as a Vehicle which can provide all the data members like steering, tires, gear etc and then we have a abstract methods in the class which can only have declaration and not the implementation like driving. We can then create a normal classes like Swift, Wagonr, Maruti which are different types of vehicles and those classed can inherit from the main class Vehicle and using the data members of the Vehicle class provide the full implementation of  driving method present in the Vehicle class. As every child class has a different implementation for the driving method hence we can override the abstract method in the child class and gives its own implementation. 

    Please find the  example below:

     public abstract class Vehicle
 
{
            public string steering { get; set;}
            
            public string tyres {get; set;}

            public string gear {get; set;}


            public abstract void driving();

  }

    public class Swift : Vehicle
    
{    
     
        public override void driving()
     {
            // Provide the implementation here
     }    


}

Few important points to remember related to abstract class in C# as below.

  • We need to declare an abstract class in C# using abstract keyword.
  • Abstract class can have abstract as well as non abstract methods.
  • Abstract methods needs to be declared with abstract keyword and they can not have implementation.
  • When we inherit any abstract class then we must implement the methods in the child class which are marked as abstract in abstract class.

So today, we saw how we can use abstract classes in C#, their importance. 

Thank You …..

For any issues related to C#, .NET or for any feedback then please write to me on below mail Id and I will surely get back to you.

Email Id : prson94@gmail.com



0 comments:

Post a Comment