<  Day Day Up  >  

An interface is a set of methods , events, and properties that a type can declare that it supports. When a type supports an interface, it is said to implement the interface. Interfaces are useful to allow types to declare general capabilities that they support. For example, the .NET Framework defines an interface, IComparable , that defines a CompareTo method.

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

A type that implements IComparable can then be compared in a general way; for example, the Framework also defines an Array. Sort method that sorts arrays. This method requires that the type of the array implement IComparable , so that the sorting algorithm can determine whether one element of the array is "less than" another element of the array. If a type does not implement the interface, it cannot be sorted in an array. The following example shows a type implementing the IComparable interface.

 Class Building   Implements IComparable   Public Height As Integer   Public Function CompareTo(ByVal obj As Object) As Integer _       Implements IComparable.CompareTo     Dim OtherHeight As Integer     If Not TypeOf obj Is Building Then       Throw New ArgumentException()     End If     OtherHeight = CType(obj, Building).Height     If Height < OtherHeight Then       Return -1     ElseIf Height > OtherHeight Then       Return 1     Else       Return 0     End If End Class 

Interface implementation is different from inheritance in that implementing an interface provides no default implementation ”instead, it simply names a set of members that the type must provide. Additionally, a type may implement as many interfaces as it wishes, while a class can only inherit from one base type. Interfaces, then, are primarily used to describe capabilities that many different kinds of types may support, while inheritance is primarily used to describe types that are closely related in some way.

 <  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: