First lets agree that an interface is analoguos to a C++ _pure_ virtual
class
with no implementation. An abstract class implies that it cannot be
instantiated but is designed to be extended. So the question becomes
when
to write an abstract class with a partial implementation vs when to
write a
pure virtual class with no implementation. And you ask for an example.
The
answer is to use an abstract class with a partial implementation when
you
must:
Defer the Final Implementation to Another More Knowledgeable Class
The quest is to find a situation where a lot of complicated logic is
implemented but the final implementation must be deferred to a more
knowledgeable class. The classic example is a quick sort routine. You
know
the algorithm but you cannot write the final implementation without
knowing
the actual ordinal behaviour of the type to be sorted. So you can write
an
abstract class with a powerful partial implementation leaving the
abstract
Compare(obj, obj) method without an implementation. The user of your
abstract class simply supplies a concrete implementaton of the Compare
method reusing the power of you quick sort algorithm. An alternative is
to
write a Sort method that takes an IComparable object that defines the
Compare method.
The downside of interfaces is that they are difficult to update. so.
In summary, if you have a well defined contract that will be implemented
by
many classes use an interface. If the contract is evolving, consider
using a
base class. Use a base class if you need to include implementation
details
such as in our generic quick sort algorithm.
Regards,
Jeff
*** Sent via Developersdex
http://www.developersdex.com ***