Wednesday, July 23, 2008

Abstract base classes and interfaces

Abstract base classes and interfaces
Often in a design, you want the base class to present only an interface for its derived classes.
That is, you don’t want anyone to actually create an object of the base class, only to upcast
to it so that its interface can be used. This is accomplished by making that class abstract
using the abstract keyword. If anyone tries to make an object of an abstract class, the
compiler prevents them. This is a tool to enforce a particular design.
You can also use the abstract keyword to describe a method that hasn’t been implemented
yet – as a stub indicating “here is an interface function for all types inherited from this class,
but at this point I don’t have any implementation for it.” An abstract method may be
created only inside an abstract class. When the class is inherited, that method must be
implemented, or the inherited class becomes abstract as well. Creating an abstract method
allows you to put a method in an interface without being forced to provide a possibly
meaningless body of code for that method.
The interface keyword takes the concept of an abstract class one step further by preventing
any function definitions at all. The interface is a very useful and commonly-used tool, as it
provides the perfect separation of interface and implementation. In addition, you can
combine many interfaces together, if you wish. (You cannot inherit from more than one
regular class or abstract class.)

0 comments: