only for RuBoard - do not distribute or recompile |
An interface is the basic mechanism by which a COM component exposes functionality. You can think of an interface as a contract. It describes what a component is supposed to do. How it does it is left up to you as the creator of the interface, to a certain degree. One of the fundamentals of COM is the idea of separating the interface from the implementation.
For instance, Example 2.1 shows an interface created in Visual Basic called Animal.
Recreating the ExampleThis source code is from a class module, Animal.cls , that you should add to a standard VB EXE project named Animals. Set the Instancing property of the class to PublicNotCreatable; this will make the class inaccessible from outside your project and means that the Animal class must be included in the project in which it is being used. |
'Animal.cls Private Enum Kingdoms Mammal = 1 Reptile = 2 Insect = 3 Bird = 4 Fish = 5 End Enum 'Returns animal kingdom. Private Function Kingdom( ) As Kingdoms End Function 'Returns the name of an animal in a string. Private Function Name( ) As String End Function 'Returns the noise the animal makes in a string. Private Function Noise( ) As String End Function
Notice that the functions in the class module animal.cls are just empty stubs. C++ programmers would recognize this as an abstract base class. This serves only to describe what the Animal interface looks like. By itself this does nothing. The interface must be implemented before it becomes useful. This is done in Example 2.2, which creates a Cow class. The Cow class implements and serves as a specific instance of the Animal class.
'Cow.cls Implements Animal Private Function Animal_Kingdom( ) As Kingdoms Animal_Kingdom = Mammal End Function Private Function Animal_Name( ) As String Animal_Name = "Cow" End Function Private Function Animal_Noise( ) As String Animal_Noise = "Moo!" End Function
|
The Animal interface is specific to a point. Animal_Kingdom can't return the string "Mammal." It has to return one of five values defined by the Kingdoms enumeration. Animal_Name and Animal_Noise are little more vague. Theoretically, they could return any string value. Therefore, it's important to remember that the documentation for an interface is a part of the contract, too. The compiler does not enforce these values.
only for RuBoard - do not distribute or recompile |