We all know about Interface and Abstract class definitions; but do we actually know the real difference and their appropriate usage.
Interface:
An Interface is a concept that refers to a point of interaction between components. A key principle of design is to prohibit access to all resources by default, allowing access only through well-defined entry points, i.e. interfaces.
Usages
1. Interfaces are used to encode similarities which the classes of various types share, but do not necessarily constitute a class relationship.
For example: a Human and a Parrot can both whistle; however, it would not make sense to represent Humans and Parrots as sub-classes of a Whistler class. Rather they would most likely be sub-classes of an Animal class, but both would implement the Whistler interface.
2. Interfaces allow to use an object without knowing its type of class, but rather only that it implements a certain interface.
For example: if one were annoyed by a whistling noise, one may not know whether it is a human or a parrot, because all that could be determined is that a whistler is whistling.
Practical Example: A sorting algorithm may expect an object of type Comparable. Thus, it knows that the object’s type can somehow be sorted, but it is irrelevant what the type of the object is.
Abstract Class
A template class that contains variable declarations, methods and other class properties, but incomplete in determining its state of real-world objects. That’s why these classes can’t be instantiated.
Usage
1. Abstract Class is used to encode similarities which the classes of various types share, also necessarily constitute a class relationship.
Example: Animal will be abstract class, as mentioned in the above examples.
Interface Vs Abstract Class:
1. Interface supports for Multiple Inheritance but Abstract class restricts.
2. Interfaces are slower than Abstract classes.
Examples:
A Parrot and A Human are animals which whistles.
Analysis: Animals is a category under which both A Parrot and A Human lies in Real world. Animal class is incomplete in determining it whole behavior, which makes this as Abstract class for both sub types Human and Parrot. All Humans and Parrots whistles, this is the common property, which makes Whistler as Interface.
Summary
If you think, requirements are not going to change in future and multiple inheritance will not be the Issue then use Abstract class.
Feel free to post comments if you have something more to add.