The syntax for defining an interface is very similar to the syntax for defining a class or a structure:
[attributes] [access-modifier] Interface identifier [interface-bases] interface-body End Interface
The optional attributes are discussed in Chapter 8. Access modifiers (Public, Private, etc.) work just as they do with classes. (See Chapter 5 for more about access modifiers.) The Interface keyword is followed by an identifier (the interface name). It is common (but not required) to begin the name of your interface with a capital I. Thus, IStorable, ICloneable, IClaudius, etc. The optional list of interface-bases is discussed in titled Section 8.5, later in this chapter.
The body of the interface is terminated with the keywords End Interface.
Interfaces Versus Abstract Base ClassesProgrammers learning VB.NET often ask about the difference between an interface and an abstract (MustInherit) base class. The key difference is subtle: a MustInherit base class serves as the base class for a family of derived classes, while an interface is meant to be mixed in with other inheritance trees. Inheriting from a MustInherit class implements the is-a relationship, introduced in Chapter 4. Implementing an interface defines a different relationship, one we've not seen until now: the implements relationship. These two relationships are subtly different. A car is a vehicle, but it might implement the CanBeBoughtWithABigLoan capability (as can a house, for example). |
Suppose you want to create an interface to define the contract for data being stored to a database or file. Your interface will define the methods and properties a class will need to implement in order to be stored. You decide to call this interface IStorable.
In this interface, you might specify two methods, Read( ) and Write( ), and a property, Status, which appear in the interface body:
Interface IStorable Sub Read( ) Sub Write(object) Property Status( ) As Integer End Interface
Note that when declaring the methods of the interface, you provide a prototype:
Sub Read( )
but no implementation and no End Function, End Sub, or End Property statement. Notice also that the IStorable method declarations do not include access modifiers (e.g., Public, Private, Protected, Friend). In fact, providing an access modifier generates a compile error. Interface methods are implicitly public because an interface is a contract meant to be used by other classes.
Top |