|
|
|
||
|
||
Polymorphism by means of Interfaces: A common way to provide polymorphism in VB is by means of Interfaces. An Interface in VB is a class module that we define as a template for the actual classes that will implement this interface. In VB an interface is just like any other class module in your project except that methods and functions have no code at all. In REALbasic an Interface is a special module that you must add to your project. In RB2006 you must select "Class Interface" from the "Add" menu under the "Project" menu.
Just like in VB you must add the empty methods to the Interface Class. A method of an Interface Class doesn't have any code. Once we define our Interface is time to implement the Interface in some other class. In VB we use the statement "Implements". This statement is followed by the name of the class interface. In REALbasic a class module has a interface property where we type the name of the interfaces separated by comas that our class will implement.
Now that our class module "dog" implements the interface "animal" we can add the necessary code to each of the methods implemented by "dog". One big different that you may have noticed already is that in VB the methods of an Interface are implemented more like events on the class module. For example the Bite method of the interface "Animal" would be declared in VB as:
In REALbasic the method is implemented with the same name as the name it has on the interface. One limitation that REALbasic has is that a class module can not implement two interfaces which have methods with the same name. The VB syntax works as a name space that avoids this problem. Notice that we can easily fix our problem by prefixing the name of the interface to the interface methods. In VB you can define a property in the Interface. The VB syntax is the same as of a variable:
In our class module that implements this interface we know have the GET/LET pair methods for the Age property defined in the Interface. In REALbasic you can not add properties to an Interface but there is an easy workaround to add properties to the Interface. In REALbasic we must add the equivalent to the GET/LET pair of methods to the Interface. To declare the LET method we do so using the assigns keyword. Lets see how this method would look like: Sub Age(assigns value as integer) The GET method is nothing more than a function:
Lets see an example of how we can use our interface in REALbasic.
|
||
|
||