views:

61

answers:

2

Whenever I create an abstract class I tend to create an interface to go along with it and have other code refer to the interface and not the abstract class. Usually when I don't create an interface to start with I regret it (such as having to override all implimented methods to stub the class for unit testing or later down the line new classes don't need any of the implimentation and override everything also finding themselves unable to extend any other class).

At first I tried to distinguish when to use an interface and when to use an abstract class by considering is-a vs able-to but I still would end up suffering later down the line for not making an interface to start with.

So the question is when is it a good idea to only have an abstract class and no interface at all?

+2  A: 

When you wish to "give" some base class functionality to derived classes but when this functionality is not sufficient to instantiate a usable class, then go for abstract classes.

When you wish that some classes completely implement a set of methods (a public contract), then it is a convenient to define such contract with interfaces and enforce them onto classes by making them inherit this interface.

In short:

With abstract classes you give some common base functionality to derived classes. No further actions are necessary unless abstract class has some stubs (which have to be implemented down there).

With interfaces you require derived classes to implement a set of functions and you do not pass along any implementation.

So the question is when is it a good idea to only have an abstract class and no interface at all?

  • When you do not wish to enforce any public contract (a set of methods/properties defined by an interface).

  • Also when you do not plan to use certain coding techniques like casting object to an interface type (run-time polymorphism) or limit allowed input (some method argument will only accept object of types which implement certain interfaces).

Developer Art
The question, as I understand it, is not abstract class vs interface. It's abstract class + interface vs abstract class.
Mehrdad Afshari
right, when to use abstract class only..
insipid
Thanks for the edit, is there a downside to going ahead and giving an interface just in case when you don't need one at the time?
insipid
I just realized that last comment is language dependent since in some languages methods always resolve to actual type and take the performance hit and in some you have a choice.
insipid
A: 

Well, the main case it is useful to have only an abstract class without any interface is to mark a certain type. It is useful to be able to check if an object "is-a" something. These interface "mark" an objet to be of a certain type. Depending on the language you use, different design patterns apply ...

These sort of abstract classes exist in java. You can also use them in C++ with RTTI.

my2c
neuro