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

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 which you encounter in almost all interviews: "Where will you use Interface and Abstract class?"  Or 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 user Interface and Abstract class but also to give an understanding in detail as well. Because both the concepts are very important.

So let’s start with Abstract Class

Abstract Class

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

  1. public abstract class AbstractCar  
  2. {  
  3.   
  4. }  
You can have both abstract and non-abstract methods in the Abstract Class. Generally we use abstract class as a base class. But you need to implement all the abstract methods in the deriver class by using override keyword. You can’t create an object of Abstract Class. Abstract class can never support multiple inheritances.

Let’s see the details example of abstract class

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 abstract class, abstract methods are not public by defaul, 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 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 methos 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 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.