Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.
An interface represents a contract, in that a class that implements an interface must implement every aspect of that interface exactly as it is defined.
With interfaces, you can define features as small groups of closely related members. You can develop enhanced implementations for your interfaces without jeopardizing existing code, thus minimizing compatibility problems. You can also add new features at any time by developing additional interfaces and implementations.
Although interface implementations can evolve, interfaces themselves cannot be changed once published. Changes to a published interface may break existing code. If you think of an interface as a contract, it is clear that both sides of the contract have a role to play. The publisher of an interface agrees never to change that interface, and the implementer agrees to implement the interface exactly as it was designed.
In previous versions of Visual Basic, you could consume interfaces but not create them directly. Now you can define true interfaces using the Interface statement
There are several other reasons why you might want to use interfaces instead of class inheritance:
• Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.
• Interfaces are more flexible than base classes because you can define a single implementation that can implement multiple interfaces.
• Interfaces are better in situations in which you do not have to inherit implementation from a base class.
• Interfaces are useful when you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces.
Inheritance is a good choice when:
• Your inheritance hierarchy represents an "is-a" relationship and not a "has-a" relationship.
• You can reuse code from the base classes.
• You need to apply the same class and methods to different data types.
• The class hierarchy is reasonably shallow, and other developers are not likely to add many more levels.
• You want to make global changes to derived classes by changing a base class.
Friday, November 6, 2009
Subscribe to:
Posts (Atom)