When to Use Interface And When To Use Abstract Class - Part One

Introduction

Nowadays, in an interview, no one asks direct questions; rather, they will give you a scenario and ask the solution for the same. And almost always there is one common question that you encounter in almost all interviews: "Where will you use Interface and Abstract class?" The interviewer will give one scenario and ask in this scenario if you will go for Abstract class or Interface and why.

My idea is to give readers an understanding of where to use Interface and Abstract classes but also to give an understanding in detail as well. Because both the concepts are very important.

Abstract Class in C#

The purpose of an abstract class is to provide the default functionality for its base class. You need to put the abstract keyword ahead of class to define it as an Abstract Class, as mentioned below,

publicabstractclassAbstractCar
{

}

You can have both abstract and non-abstract methods in the Abstract Class. Generally, we use the abstract class as a base class. But you need to implement all the abstract methods in the derived class by using the override keyword. You can’t create an object of Abstract Class. An abstract class can never support multiple inheritances.

Example

class

Now we move on and see a few important things about “Abstract Class,” let’s take it one by one.

  1. We will try to create an object of Abstract Class and see what happens.
    create
    So that means we can’t create an object of Abstract Class.
  2. Interface will not provide any access specifier to the abstract method.
    method
    It means in the abstract class, abstract methods are not public by default; it's private by default. The access modifier of the abstract method should be the same in both the abstract class and in its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.
  3. Like interface will not provide any access specifier to the abstract method.
    method
    We can define Delegates, Properties, etc. in Abstract Class.
  4. Abstract Properties
    Properties
    code
  5. You need to implement all the abstract methods in a derived class,
    class
    I got the above error because I have not implemented all the methods in the derived class. So it’s mandatory to implement all the abstract methods and properties in the derived class.

Conclusion

I hope this article helps you to explore all the possibilities of Abstract Class. In case not, please drop me a note, and I will explore it further. In the second article, I will talk about Interface and will give more focus on where to use it.


Similar Articles