Saturday, June 4, 2016

Abstract class vs Interface

This is one of the most common questions which is being asked in interviews - what is the difference between the abstract class and and interface. And different answers include the use related to multiple inheritance, abstract/non-abstract methods, no instance creation for abstract class etc. These are fine, but one of the most important answer which I feel is the real difference i.e. which one should be used when, is normally not answered properly. In this article we will try to see what is should be.

An abstract class is aimed at
  1. Providing the functionality of a base class with some functionality which we want to force the derived classes to use.
  2. Provide abstract methods, which the derived classes can implement as per their own requirement.
The first point here is the important one. It is not necessary that we use the abstract class to have abstract methods. It's just optional. However, the point whether we should use abstract class or an interface, can be decided by considering both the points above.

For ex. we can have an abstract class with an abstract method say SaveData and a non abstract method named CreateDatabaseConnection, which is used for database connectivity. Two classes ClassA and ClassB derive from this abstract class and must provide their own implementations of the SaveData. However, they must use the same CreateDatabaseConnection method. This is where we should use the abstract class rather then the interface.

So, an abstract class provides the functionality of a base class as well as contain abstract methods, which must be implemented by the derived classes. However, this is not the case with the Interfaces. They can only have method definitions and no method with complete definition.

So I guess this should be the main point to be considered while deciding whether to use an abstract class or an interface.

Hope you enjoyed reading it. Happy coding...!!!

1 comment:

  1. So, we can also say: a class can inherit only from 1 class, but it can implement from 1, 2 o more interfaces.

    ReplyDelete