Understanding ClassesIf you have used custom controls in a Visual Basic program, you have already used classes and objects. For example, when you draw a text box on a form, you are actually creating a specific instance of the text box class. For example, if you draw five text boxes on your form, you have created five instances of the text box class. Even though each instance is a distinct entity, they were all created from the same template. Instances of a class are known as objects. Each different class is a template from which a specific type of object is created. In this example, the text box class defines that a text box has a Text property. However, the class definition itself does not contain information about the values of the properties.. Instead, an object you create from the class, for example, txtLastName, actually contains information. Object-Oriented ProgrammingYou probably have heard the term object-oriented programming (OOP) or read about it in programming books and magazines. A key element of OOP is its use of reusable objects to build programs. OOP begins in the design stage, when you determine the objects in an application. For example, suppose you have to write a system to manage paychecks for employees. A traditional design plan would be to determine each program function, such as Adding an employee to the database or Printing an employee paycheck. An object-oriented design would instead try to separate programming tasks along the lines of the objects in the program (employees, database, paycheck, and so on). In order for a design to be considered object-oriented, several facts must be true about the objects. These fundamental concepts of OOP are summarized in the following list:
An important consequence of an OOP approach is reusable code. Part of what makes an object reusable is its interface, or the methods and properties the object uses to communicate with the outside world. If you build objects with well-defined interfaces, it is easy to change the object internally or even add new interfaces without affecting programs that use the object. Classes in Visual BasicYou create your own classes in Visual Basic with a class module. Class modules can contain several types of elements:
Class modules also contain two special events of their own, Initialize and Terminate. The Initialize event is triggered when a new instance of the class is created, and the Terminate event occurs when the object is destroyed. Object definitions are created in a class module. A class module is like a standard code module in that it contains only variable declarations and procedure code. There is no user interface component of a class module. However, a class can take action using a form that is in the program, just like a normal code module. Class modules can be used in several ways, such as the following:
|
|
![]() |
![]() |
|||