Interfaces and implementation5.3
An interface is a boundary between two objects. In programming terms this means that an object can follow a set of rules.
An interface can be seen as very similar to an abstract class in that it specifies rules, but unlike an abstract class it cannot have any methods specified.
An interface is like a class with the rules that all classes that use it must include and given functionality to. The
Interface keyword is used to declare an interface.
Interface Game Sub InitiateGame() Sub SaveGame() End Interface
The interface specifies nothing about what the program does, but it specifies how it should be implemented.
An interface needs to be used using an implementation, the class that contains the interface
cannot be used on its own. This is done using the
Implements keyword in
a similar fashion to
Inherits being used with a class.
Public Class DragonGame Implements Game Sub InitiateGame() Implements Game.InitiateGame 'Place code to run game here End Sub Sub SaveGame() Implements Game.SaveGame 'Place code to save game here End Sub End Class
This class can now be used as one that falls into the type of class required as a
Why interfaces are useful
Interfaces may just seem like worse versions of abstract classes, but as a matter of fact they are actually more interesting than that.
The difference however is that a class can implement more than one interface and be accepted as any of such interfaces. With inheritance, a class may only inherit one class.
The following sample taken from this website
tests an interface called
interface against the
Game interface and if it finds that it
Game interface it will run the
If GetType(interface).IsAssignableFrom(Game) Then 'Start the game CType(MyObject, IMyInterface).InitiateGame() End If
This article on CodeProject has more on the differences between abstract classes and interfaces.