Sunday, November 16, 2008

Differences between an Abstract Class and an Interface

An Abstract class without any implementation just looks like an Interface, so what is the significance of using Interfaces instead of an Abstract classes?

The concepts of Abstract classes and Interfaces are always confusing to the beginners of OOP, though they have been through all the theories. Therefore, in this post, I have tried to discuss these two things.

An Abstract class is a special kind of class that cannot be instantiated. It only allows other classes to inherit from it but cannot be instantiated. When we create an abstract class, we are creating a base class that might have one or more completed methods but some methods can be left uncompleted.

An Interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body.

An interface is similar to an abstract class. Both types must be inherited. You cannot create an instance of either. Abstract members require implementation in the derived type. Interface members require implementation in a derived type. Although abstract and interface members are similar, there are several differences:

  • An abstract class can contain some implementation. Interfaces have no implementation.

  • Abstract classes can inherit other classes and interfaces. Interfaces can only inherit other interfaces.

  • Abstract classes can contain fields. Interfaces cannot have state.

  • Abstract classes have constructors and destructors. Interfaces have neither.

  • Interfaces can be inherited by structures. Abstract classes are not inheritable by structures.

  • Interfaces support multiple inheritance. Abstract classes support single inheritance.

If all the methods of an abstract class are uncompleted then it is same as an interface. And everyone knows that an abstract class can provide some defoult behaviors to the sub-classes which an Interface cannot. But if we can have a complete abstract class (which looks like an Interface), then why the heck do we need Interfaces?

The answer is, most of the Object Oriented Languages do not support multiple inheritance. But, it is obvious that sometimes we need a class to have behavior like more than one class, and the language is not supporting that- we cannot extend more than one class. So, to provide this feature of multiple inheritance, we need interfaces, because it is possible for a class to implement multiple interfaces.

No comments: