CLASSES AND OBJECTS


As I have already stated, a class is a template that defines all of the attributes, properties, methods, and events required to create an object. Using abstraction, programmers develop a design for a class. Using encapsulation, they implement a class structure. One class can be established by inheriting it from another class. Finally, using overloading, programmers can extend procedures within classes to handle different sets of arguments.

For example, you might analogize the relationship between a class and an object as being akin to the relationship between a mold and Jell-O. The mold defines an overall form and shape of the Jell-O. Once poured into the mold and solidified, the new instance of Jell-O takes on the basic qualities of the mold. As another, more specific, example, the Form object is an instance of the Form class and has access to all the features provided by that class.

In order to use a class, you must first instantiate it. The instantiation process varies depending on the class you are working with. For example, to instantiate a Button or Checkbox class (control), all that you have to do is place a copy of it on a form. However, if you create your own custom class as part of a Visual Basic application, you will create a new class instance using the New keyword.

Creating a New Class

There are a number of ways that you can create a new class. First, as you have already seen, anytime you create a new Visual Basic application, a new class is created for you based on the System.Windows.Forms.Form class. In the case of the Dice Poker game, the new class was named frmMain.

You can also add a new class to an application by simply inserting its declaration under the existing class definition in the code editor, as shown below.

 Public Class frmMain     Private Sub frmMain_Load(ByVal sender As System.Object, _        ByVal e As System.EventArgs) Handles MyBase.Load     End Sub End Class Public Class Greeting End Class 

In this example, a new class named Greeting has been defined. At the moment, the class does not have any data members, properties, or methods defined to it.

Let's continue on with the previous example, adding a little code to give the Greeting class a little functionality. Modify the example as shown below, starting with the code in the Greeting class and then adding the two statements inside the frmmain_Load event procedure.

image from book
DEFINITION

A data member is a variable that is defined within a class. Ordinarily, data members are hidden from the outside world and used only within the class. However, data members can be made directly accessible from outside the class using the Public keyword.

image from book

 Public Class frmMain     Private Sub frmMain_Load(ByVal sender As System.Object, _        ByVal e As System.EventArgs) Handles MyBase.Load         Dim SampleGreeting As New Greeting         MessageBox.Show(SampleGreeting.Message)     End Sub End Class Public Class Greeting     Public Message As String = "Hello World!" End Class 

The statement that you added to the Greeting class sets up a data member. Data members are by default private, meaning that they cannot be accessed from outside of the class itself. However, in this example, I made the data member public just so that we could have a working example that does something.

By itself, the Greeting class does not do anything. You need to instantiate an object based on the class in order to be able to do something. The first statement in the frmMain_Load event procedure instantiates a new object named SampleGreeting using the New keyword, which follows the syntax shown below.

 Dim ObjectName As New ClassName 

Then the MessageBox.Show method is used to access and display the SampleGreeting object's Message data member.

Another way to add a new class to your application is to create it in its own code module, separate and distinct from the form's class code, as demonstrated in the following example.

  1. Click on the Add Class option located on the Project menu. The Add New Item window appears, as shown in Figure 9.6.

  2. Select the Class icon and type a name for the class that you are about to define in the Name field, and then click on the Add button.

  3. A new tab will appear in the code editor, and the opening and closing class statements for the new class will be displayed, as shown in Figure 9.7.

  4. Modify the program code for the Greeting class as shown below.

     Public Class Greeting     Public Message As String = "Hello World!" End Class 

image from book
Figure 9.6: Defining a new class in its own code module.

image from book
Figure 9.7: Viewing the code that Visual Basic automatically created for the new class.

Now, if you run this example, you will find that it displays the same results as the example in which you embedded the Class definition beneath the bottom of the frmMain class.

Understanding Data Members

In the previous two examples that demonstrated how to create a new class, you learned how to define a new data member. By default, class data members are private, which means that they cannot be seen or accessed from outside the class. However, as the examples showed, you can make data members publicly available. You can also declare them as protected, in which case they can be accessed only by derived classes of the base class.

Although it is possible for data members to be accessed from outside the class, they are not properties of that class. However, when made publicly available, you lose the ability to restrict control over data members. Instead of making data members public, you should keep them private and set up properties to provide controlled access to any data stored in your classes.

Defining Class Properties

Properties can be used to set and retrieve values. To set up a property within a class, you start by declaring a private data member and then define a public property procedure that provides controlled access to the value stored in the data member. The following types of property procedures are supported by Visual Basic.

  • Get. Retrieves the value assigned to a property

  • Set. Assigns a value to a property

The following example demonstrates how to add a property to a class.

 Public Class Greeting     Private Message As String     Public Property Text() As String            Get                 Return Message            End Get            Set(ByVal Value As String)                 Message = Value            End Set       End property End Class 

As you have seen throughout this book, before you can use an object, you must instantiate it. You can then reference its properties by specifying the name of the object, followed by a period and the name of a particular property. When you assign a value to the Text property, the Set property procedure block executes. Note that the Set property procedure is automatically passed an argument named Value in which the data passed to the Set property procedure is stored. All you have to do to finish up the property assignment is to assign the data stored in Value to a private data member (Message). When you retrieve the value associated with the Text property, the Get procedure block is automatically executed.

The following statements demonstrate how to derive an object from the Greeting class and then set and retrieve the object's Text property. The first statement shown below instantiates a new object named SampleGreeting that is derived from the Greeting class. The next two statements assign a value to the object's Text property and then use the MessageBox.Show method to demonstrate that the property assignment was successful.

 Dim objSample As New Greeting objSample.Text = "Good Morning." MessageBox.Show(objSample.Text) 

As I mentioned earlier, the advantage of setting up properties, compared to simply making data members public, is that you can add code to your property procedures to perform data validation before allowing access to the data associated with a particular property. As a quick example of how this works, I have modified the previous example, shown below, to include such a check.

 Public Property Text() As String          Get              Return Message          End Get          Set(ByVal Value As String)              If Len(Value) > 2 Then                  Message = Value              End If          End Set End Property 

This new example now requires that a property assignment for the Text property be at least two characters in length.

Adding Class Methods

In addition to defining data members and properties in your custom classes, you can add your own methods. To add a method to a class, all you have to do is add a Sub or Function procedure, as demonstrated below.

 Public Class Greeting     Private Message As String     Public Property Text() As String         Get              Return Message         End Get         Set(ByVal Value As String)             If Len(Value) > 2 Then                 Message = Value             End If         End Set     End Property     Public Sub PostWelcome()         MessageBox.Show("Welcome to my Visual Basic application!")     End Sub End Class 

In this example, the Greeting class has been modified by the addition of a method named PostWelcome(). When executed, this method uses the MessageBox.Show method to display a text message. Like all of the other object methods that you have worked with, you can call on this method by specifying the name of its object followed by a period and the name of the method, as shown below.

 Dim objSample As New Greeting objSample.PostWelcome() 

One of Visual Basic's object-oriented programming features is polymorphism. Polymorphism is implemented in Visual Basic by providing the ability to overload class methods.

When you overload a method, as demonstrated below, Visual Basic makes sure that the correct method is executed based on the argument list that is passed.

 Public Class DisplayMessage      Public Overloads Sub Display(ByVal Message As String)           MessageBox.Show(Message)      End Sub      Public Overloads Sub Display(ByVal Message As String, Title As String)           MessageBox.Show(Message, Title)      End Sub End Class 

In this example, two Sub procedures, both of which are named Display, are defined. Notice the use of the keyword Overloads in both Sub procedure definitions. The first Sub procedure is designed to process a single argument, whereas the second Sub procedure is designed to process two arguments.

Trick 

For overloading to work, you must provide each overloaded procedure with a unique set of arguments. You can vary the argument list by changing the number of arguments that are passed, by changing the types of argument passed, or a combination of both.

Inheriting from Another Class

Anytime Visual Basic provides you with a new form, behind the scenes the new instance of the form is created by specifying the Inherits keyword and the name of the class that is to be inherited from, as shown below.

 Partial Public Class frmMain   Inherits System.Windows.Forms.Form 

The derived class inherits its features from the base class. Anytime you add a control to a form, Visual Basic automatically handles the setup of the new instance of the control (object). In addition to inheriting from classes provided to you by Visual Basic and the .NET Framework, you can derive new classes from classes that you create. The following example demonstrates how to create a new class named GreetingTwo using the Greeting class as the base class.

 Public Class GreetingTwo     Inherits Greeting     Private Warning As String = "Action not allowed."     Public Readonly Property ErrMsg() As String         Get              Return Warning         End Get     End Property End Class 

You'll notice that the GreetingTwo class not only inherits all of the properties and methods belonging to the Greeting class, but also extends this functionality by adding a new property of its own. In addition, you'll notice that the new ErrMsg property has been made read-only, meaning that it can be retrieved but not modified by calling statements.

Any objects created using the new GreetingTwo class automatically inherit all of the properties and methods from the GreetingTwo class, which itself includes methods and properties inherited from the Greeting class.




Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
ISBN: 1592008143
EAN: 2147483647
Year: 2006
Pages: 126

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net