Additional Interface Topics
Interfaces are a deep topic within Visual Basic .NET. You’ve now seen how to declare your own interfaces and then to program classes to implement those interfaces. This section covers a few additional interface topics so that you know they exist; you can read about them further when you think they might help you solve a particular problem.First, a single class can implement more than one interface. Perhaps you’ve deduced this fact already because you learned that a class that implements a single interface can declare additional members outside the interface to provide further functionality. Why not, then, have a class that implements multiple interfaces? A class definition might look like the following:
Public Class ISpaceInvadersGuy
Implements IPCOpponentGamePiece, IEnumerable, IComparable
<lots of code removed>
End Class
This class implements three different interfaces—the game piece interface discussed in this chapter and the two .NET Framework interfaces IEnumerable and IComparable.Second, interfaces can inherit from each other just like classes can. Consider the legal interface definitions shown in Listing 6-13.Listing 6.13: Inheriting Interfaces
Interface ITwoDimensionalObject
Property Width() As Integer
Property Length() As Integer
Property xCoord() As Integer
Property yCoord() As Integer
Sub MoveLeft(ByVal iHowFar As Integer)
Sub MoveRight(ByVal iHowFar As Integer)
Sub MoveForward(ByVal iHowFar As Integer)
Sub MoveBackward(ByVal iHowFar As Integer)
End Interface
Interface IThreeDimensionalObject
Inherits ITwoDimensionalObject
Property Height() As Integer
Property zCoord() As Integer
Sub MoveUp(ByVal iHowFar As Integer)
Sub MoveDown(ByVal iHowFar As Integer)
End Interface
The first interface declares some properties for a two-dimensional object and some simple methods to move that object. The second interface extends the first one and adds properties and methods that help describe a three-dimensional object. You could use the first interface to implement classes for your two-dimensional game and then use the three-dimensional interface when it comes time to define classes for your first Quake clone or similar first-person shooter.Defining interfaces in this way gives you all the benefits of inheritance. If you add a member to the two-dimensional interface, all of the classes that implement this interface as well as the three-dimensional interface will be required to implement this member before these classes will compile.This chapter has shown you the power and structure that developing to interfaces gives you.