Abstract vs Interface

From CSSEMediaWiki
Revision as of 03:31, 3 August 2010 by LukeRobinson (Talk | contribs)
Jump to: navigation, search

We all know that we should program to the interface not the implementation. But what is an interface? and how do we know what kind of interface to use?

You might think the answer is simple, and many times it is, but there is a case where the line becomes hard to distinguish.

That case is known as Abstract vs Interface.

The question is should I use an abstract base class or implement an interface? After all, they are both programing to the interface not the implementation.

In the example below, each "Agent" has one communication device, but it may be a cellphone, computer or pager. To contact an agent, we can just pass the message we want to send to their communication device.

Interface.png Abstract.png

But which is the right design to use? The one with an abstract base class or the one with an interface?

There is no one rule about which to use, but here are some things to think about when you decide which to use in your design.

Personal tools