Thursday, February 20, 2014

Interface vs. Abstract class.

One of my friend asked a question, what is the difference between an Interface and Abstract class. He asked when and where to use interface & abstract classes. I replied and thought the same would be helpful to others also hence turned into a blog post.

Here is what I replied.

Both Interface and Abstract class can be used wherever you need a contract.

However the Interface is purely for contract purposes w/o any concrete implementation but Abstract class can have some default behavior/attributes implemented. Still the abstract class need to be inherited but can provide some common functionality across varieties/specialization/role etc..

Interface has one advantage over abstract class. You can use it for multiple implementation inheritance. You cannot inherit from more than one class/abstract classes. You can have a class deriving from zero or one class and implementing more than one Interface.

Mostly both are there for specifying specialize the object capabilities. Like a bird that can Fly and Quack. But these capabilities should be modeled in separate Interfaces. If you put both in single class then and derive this class by one bird which cannot fly would unnecessarily fly!!!

Indeed objects plays roles and roles have responsibilities. Object can have different capabilities too. These should be modeled using Interfaces. For example: a Person can be a Son, Father, Employee, Manager, Driver, other Social activist. That means playing different roles in different situations. We cannot model all of these things in single object. We cannot push all of these roles and capabilities into single class. doing this leads to bloating and increases the complexity.

I don't encourage Inheritance. Inheritance leads to strong coupling. Using interfaces you can high cohesion. Instead of using Inheritance, use object composition. Wherever possible avoid Inheritance and favor composition.

Objects relationships also plays much role in this. like IS-A and HAS-A, Always favor HAS-A relationship. Avoid IS-A relationship.

So using Interfaces we can model and define individual capabilities of the object and then implement them in its own class, and finally compose them to form an Object with the only required roles/capabilities/specialization.

Object roles, capabilities, specializations can be better modeled using Interfaces. Examples of object capabilities modeled as Interfaces: Flyable, Enumerable, Quackable, Printable, Observable, Groupable, Rotatable etc.

My Presentations on OOD:

Object Oriented Design: Part-1
Conditionals and Polymorphism


No comments:

Post a Comment