Chapter 14. Interfaces

 <  Day Day Up  >  

In the previous chapter, we discussed inheritance as a way of abstracting common attributes of types into base types. Inheritance is a good way of expressing the essential nature of a type; for example, an Employee is a Person and a Manager is an Employee . But because types can only have a single base class, inheritance cannot be used to express general capabilities of types. For example, many types are "comparable," which is the property of having values that can be "less than" or "greater than" other values. (For example, both numbers and dates are comparable types.) Comparable types have many useful attributes, not the least of which is that they can be sorted into an order.

However, inheritance is usually not sufficient to express the " comparability " of a type. In an order-tracking system, a Customer object may be comparable on the basis of the customer's CustomerID , while an Order object may be comparable on the basis of the order's OrderID . However, it would probably not make sense to have both the Customer object and the Order object share the same base class, because they share no other attributes. Even worse , comparability is not the only capability that a type can express. Another capability that a type can have is "enumerability," which is the property of containing values that can be enumerated using the For Each statement. An Order object may also be enumerable, allowing the For Each statement to enumerate through the various products that make up the order. Because Order can only inherit from a single base class, it isn't possible to express both comparability and enumerability through inheritance.

Interfaces allow types to support general capabilities without having to be limited by inheritance. An interface defines a set of methods , properties, and events that make up a particular capability, such as comparability. For example, comparability is defined in the .NET Framework through the System.IComparable interface.

 Interface IComparable   Function CompareTo(ByVal obj As Object) As Integer End Interface 

In this case, the IComparable interface defines a method, CompareTo , that a "comparable" type must supply. Any type that implements this interface can be considered comparable, irrespective of its base types.

 <  Day Day Up  >  

The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: