Abstract Classes and Interfaces

abstract

a. An Abstract class is a class which cannot be instantiated and  at least  one of its behavior is abstract. Suppose you want to make a class called Car and there are different types of car like maruti, lambhorgini, mercedes which all accelerate but they have their own way of accelerating. So, you have to have specific ‘accelerate’ method in all the class viz Maruti, Lambhorgini, Mercedes. That said, if we now assume that the way to fill the fuel tank in all the cars are same, then we can have a single method ‘fillFuel‘ in the base class which will be shared amongst all Maruti, Lambhorgini and Mercedes car.

Hence, the car class will have definition and declaration of the method called as ‘fillFuel’. However, it will have only declaration for the ‘accelerate’ method.

Car

car class (Abstract class)

Maruti

maruti class

Mercedes

mercedes Class

In short, if you do not have implementation of atleast 1 of the methods of a class, then that method is to be declared abstract  method and the class as Abstract Class.

Abstract keyword is like a contract which says that the first non-abstract Class that extends the Abstract class directly or indirectly must have  implementation of all the methods marked as abstract.

b. Interfaces are also  like abstract class. However they are actually pure abstract class. What it means is that it has got all methods as abstract. So if suppose, in the example of the Car, the fillFuel method was also supposed to be specific for all types of Car, then you will have even fillFuel method as abstract. Here you can use Interface like below.

Car Interface

Car Interface

Maruti Class

Maruti Class

Mercedes Class

Mercedes Class

 

Interview Question:

a. What is the difference between an Abstract Class and an Interface

An Abstract class can have non-abstract methods. Whereas, an Interface will have all methods as abstract.

b. Which one is more preferred?

Interfaces are more preferred compared to Abstract classes since you can achieve multiple inheritance using Interfaces. You  can extend only one class but you can implement multiple Interfaces