Wednesday, September 9, 2009

Abstract Class v/s Interface

While designing software systems we often come across the situation where we need to decide on having interfaces or abstract class. To help on this following are few points which can be think upon to arrive at an informed decision:

1. Interfaces are the contracts which contain the signature/declaration of the functions which are forced to be implemented by the deriving classes. Abstract class needs atleast one function that remains abstract and all other functions can be implemented in the abstract class itself.

2. Interfaces are strongly coupled design and abstract class provides more flexibility in terms of implementation. Abstract classes may also provide members that have already been implemented. Therefore, you can ensure a certain amount of identical functionality with an abstract class, but cannot with an interface.

3. You should use abstract class when there is certain implementation uncertain to its subclass and other part of the behavior is same for all of the subclass.

4. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.

5. Abstract classes are helpful while designing large functional units and interfaces shall be used while designing small, concise bits of functionality.

6. In case the requirement is to provide common, implemented functionality across all implementations of your component, use abstract classes. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.