Programming Microsoft Visual Basic 6
Chapter 6
Classes
and Objects
Inheritance
Inheritance is the ability, offered by many OOP languages, to derive a new class (the derived or inherited class) from another class (the base class). The derived class automatically inherits the properties and methods of the base class. For example, you could define a generic Shape class with properties such as Color and Position and then use it as a base for more specific classes (for example, Rectangle, Circle, and so on) that inherit all those generic properties. You could then add specific members, such as Width and Height for the Rectangle class and Radius for the Circle class. It’s interesting to note that, while polymorphism tends to reduce the amount of code necessary to use the class, inheritance reduces the code inside the class itself and therefore simplifies the job of the class creator. Unfortunately, Visual Basic doesn’t support inheritance, at least not in its more mature form of implementation inheritance. In the next chapter, I show how you can simulate inheritance by manually writing code and explain when and why this can be useful.
Your First Class Module
Creating a class in Visual Basic is straightforward: just issue an Add Class Module command from the Project menu. A new code editor window appears on an empty listing. By default, the first class module is named Class1, so the very first thing you should do is change this into a more appropriate name. In this first example, I show how to encapsulate personal data related to a person, so I’m naming this first class CPerson.
Note I admit it: I’m not a fanatic about naming conventions. Microsoft suggests that you use the cls prefix for class module names, but I don’t comply simply because I feel it makes my code less readable. I often prefer to use the shorter C prefix for classes (and I for interfaces), and sometimes I use no prefix at all, especially when objects are grouped in hierarchies. Of course, this is a matter of personal preference, and I don’t insist that my system is more rational than any other.
The first version of our class includes only a few properties. These properties are exposed as Public members of the class module itself, as you can see in this code and also in Figure 6-1 on the following page:
‘ In the declaration section of the CPerson class module
Public FirstName As String
Public LastName As String
next page....
|