Comparing Abstract Classes to Interfaces

Before interfaces existed, abstract classes were used to solve the same kinds of problems interfaces can now solve. How Microsoft elected to invent interfaces when many programmers already used abstract classes is a conversation I was not privy to.

Interestingly enough, abstract classes and interfaces solve similar but orthogonal problems. Abstract classes allow you to define an interface with or without a partial implementation; interfaces do not allow you to provide any implementation. The fact that abstract methods and interface methods have no implementation is where they are identical. Where interfaces and abstract methods are orthogonal is where you will find abstract methods and interface methods .

Abstract methods span a vertical inheritance tree, and interfaces span horizontally across different kinds of objects. Use abstract methods (that is, MustOverride methods) when you are defining behaviors that are shared across classes that have a common ancestry. Use interfaces when you are describing behaviors that span classes that do not share a common ancestry.

For example, a class Automobile may describe an abstract method Start , but there is no such car called just "automobile." A derived class, Maserati , is a kind of car and as such would need to provide an implementation of the method Start . Automobile is clearly an abstract class, and Maserati is a specific subclass. Hence we are referring to abstract methods and inheritance.

Consider an alternate example. The volume on a television can be attenuated by pressing a button on the television or by pressing a button on a remote control device. The television and the remote control do not share a common ancestry. We would not say a remote control is a television or vice versa. Thus the remote control and television share a common interface; perhaps we would refer to this interface as the IControl interface. Both the remote control and the television itself would provide a set of controls for attenuating the volume and related state values, like the channel.

Here are some basic guidelines to remember when comparing abstract classes and interfaces.

  • Abstract classes may be partially implemented, but interfaces never are.

  • Classes support single inheritance; interfaces support multiple inheritance.

  • If you inherit from an abstract class, all children are updated when the parent is updated. Interfaces are invariant; once you release an interface you should never modify it.

  • If the behavior spans different kinds of objects, use an interface. For similar kinds of objects, use abstract classes.

  • Use interfaces to support a little additional functionality, and use abstract classes for large related functionality.

Visual Basic. NET Power Coding
Visual Basic(R) .NET Power Coding
ISBN: 0672324075
EAN: 2147483647
Year: 2005
Pages: 215
Authors: Paul Kimmel © 2008-2017.
If you may any questions please contact us: