Home

Introduction to Classes

 

Programmer-Defined Types

 

Introduction

In the Visual Basic language, you can combine a group of variables into an entity. These variables become considered as one. You can then declare one or more elaborate variables from this enhanced type. Such a new type is called a class.

HomePractical Learning: Introducing Classes

  1. Start Microsoft Visual Basic and create a Console Application named DepartmentStore1
  2. In the Solution Explorer, right-click Module1.vb and click Rename
  3. Set the name to DepartmentStore.vb, press Enter, and accept to rename the file
  4. Change the document as follows:
     
    Public Module DepartmentStore
    
        Public Function Main() As Integer
    
            Return 0
        End Function
    
    End Module
  5. Save the file
 

Creating a Class

Imagine you want to represent a rectangle as a geometric object:

Rectangle

You can declare each of its various parts as a variable. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim RectLength As Double
        Dim RectHeight As Double

        RectLength = 24.55 : RectHeight = 20.75

        MsgBox("=-= Rectangle Characteristics =-=" & vbCrLf & _
               "Length: " & vbTab & RectLength & vbCrLf & _
               "Height: " & vbTab & RectHeight)

        Return 0
    End Function

End Module

This would produce:

Class

If you want to treat the whole rectangle as one object, you can create a class for it. To create a class, you can use the Class keyword followed by a name. The name of a class follows the rules we have applied so far for variable and function names. To declare a class called Rectangle, you would start with the following:

Class Rectangle

As a name that represents a group of items, a class has a body that would be used to define the items that compose it. The body of a class starts after its name. 

To indicate the end of the class, type End Class. Therefore, a class can be created as follows:

Class Rectangle

End Class

Since a class is a combination of other variables, you declare each variable inside of the body of the class. Each item that composes the class is represented as a complete variable declared with a name and a data type. By adding a Length and a Height variables, our class would become: 

Class Rectangle
    Dim Length As Double
    Dim Height As Double
End Class

The items that compose a class are called members of the class. When creating the members of a class, you can omit the Dim keyword:

Class Rectangle
    Length As Double
    Height As Double
End Class

To create a class in Microsoft Visual Studio:

  1. On the main menu, you can click Project -> Add Class... Alternatively, in the Solution Explorer, you can right-click the name of the project, position the mouse on Add, and click Class
  2. In the Templates section of the Add New Item dialog box, make sure the Class item is selected. Accept the suggested name or replace it in the Name text box
     
  3. Click Add

HomePractical Learning: Introducing Class Members

Imagine you want to write a (console-based) program for a department store and the customer has given you a preliminary catalog as follows:

Crinkled georgette dress with empire waist, sequined corsage. Raw-edge pieced appliques on skirt. Buttoned keyhole back; 23" from waist. Rayon; lined. Dry clean. Imported. New Wool Comfort Pants Pencil Skirt
Stock #: 437876
Crinkled Georgette Dress
Unit: $42.95
Stock #: 790475
New Wool Comfort Pants
$38.75
Stock #: 740797
Pencil Skirt
$25.75
Silver 1/10-ct. T.W. Diamond Heart-Link Bracelet Multistriped Organic Cotton Dress Shirt Modest Dress Heels
Stock: 608432
Silver 1/10-ct. T.W. Diamond Heart-Link Bracelet
$95.85
Stock #: 759470
Multistriped Organic Cotton Dress Shirt
$35.50
Stock #: 487046
Modest Dress Heels
$35.50

Each item in this catalog is represented by its Stock number, its name or description, and its price. Based on this, you can create a class that represents each item.

  1. To create a new class, on the main menu, click Project -> Add Class...
  2. In the Templates section of the Add New Item dialog box, make sure the Class item is selected.
    Set the Name to StoreItem
  3. Click Add
  4. Change the document as follows:
     
    Public Class StoreItem
        Dim ItemNumber As Long
        Dim ItemName As String
        Dim UnitPrice As Double
    End Class
  5. Save the file

Class Members and Access Modifiers

 

Introduction

In Lesson 4, we saw how to control access to members of a module. When you create a class, you also exercise this control. You define what member variables can be accessed from outside the class and members that must not be accessed outside. This means that when creating a class, you specify what members are friendly, public, or private.

The Friendly Members of a Class

A member variable of a class is referred to as a friend if it can be accessed by any class or module of the same application. Classes and modules outside of its application cannot access such a member. To create such a member variable, precede it with the Friend keyword. Here is an example:

Class Rectangle
    Friend Height As Double
End Class

HomePractical Learning: Controlling the Access Level

  1. To specify the member variables as public, change the file as follows:
     
    Public Class StoreItem
        Friend ItemNumber As Long
        Friend ItemName As String
        Friend UnitPrice As Double
    End Class
  2. Save the file 

The Public Members of a Class

Some of the member variables of a class must be accessed outside of a class and sometimes you will want a member to be accessible outside of its application. Such a member is referred to a public. To create a public member of a class, precede it with the Public keyword. Here is an example:

Class Rectangle
    Public Length As Double
    Friend Height As Double
End Class

Classes and Access Modifiers

 

Introduction

In Lesson 4, we saw how to control access to a module. You can exercise the same level of control for a class. You can make a class friendly, private, or public.

A Private Class

If you create a class in a code file but the class must be accessed only locally, you can define it as private. A class is referred to as private if it can be accessed only within the module where it is created, that is, only by members of the same file. Classes and modules outside of its file or outside of the application cannot access such a class.

To create a private class, precede it with the Private keyword. Here is an example:

Module Exercise
    REM This class can be accessed only inside this module
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        
        Return 0
    End Function

End Module

A Friendly Class

Instead of hiding a class from the rest of the application, you may want other modules or classes of the same application to have access to it. Such a class is referred to as friendly. A friendly class can be accessed by code within its application. Classes and modules outside of its application do not have access to such a class.

To create a friendly class, precede it with the Friend keyword. Here is an example:

Friend Class Square
    Public Side As Double
End Class

A Public Class

Although you may think of working only in Visual Basic, in some cases, you may create a class and want to share it with code written in another language such as C++/CLI or C#, to make this possible, you can give "public" access to your class.

If you want your class to be accessible to code written in other languages, precede the Class keyword with Public when creating it. Here is an example:

Public Class Circle
    Friend Radius As Double
End Class

Using a Class as a Variable

 

Introduction

After creating a class, to use it in a program, you can declare it as a variable. Here is an example:

Module Exercise
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        Dim Recto As Rectangle

        Return 0
    End Function

End Module

After declaring the variable, you must ask the compiler to reserve enough memory for all the member variables of the class. The compiler would do this. Later on, to access any member variable of the class, you must get a reference to the area of memory where the members of the class are located. To do this, when declaring the variable for the class, to reserve the necessary area of memory, use the New operator followed by the name of the class and assign this expression to the variable. Here is an example:

Module Exercise
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        Dim Recto As Rectangle

	Recto = New Rectangle

        Return 0
    End Function

End Module

Instead of first declaring the variable before allocating memory for it, you can take care of this directly when declaring the variable by inserting the New operator between the As keyword and the name of the class. This can be done as follows:

Module Exercise
    
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        Dim Recto As New Rectangle

        Return 0
    End Function

End Module
Author Note In C++ and Visual Basic, you can omit or add parentheses to the name of the class when allocating memory for it, like this:
Module Exercise
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        Dim Recto As Rectangle

	Recto = New Rectangle()

        Return 0
    End Function

End Module

or like this:

Module Exercise
    
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        Dim Recto As New Rectangle()

        Return 0
    End Function

End Module

In C#, you must always use parentheses.

Any of these techniques produces the same result. It is just a matter of taste. A variable declared of a class is also called an object.

HomePractical Learning: Creating an Object

  1. Access the Program.vb file and declare a variable as follows:
     
    Public Module DepartmentStore
    
        Public Function Main() As Integer
            Dim dptStore As StoreItem
    
            dptStore = New StoreItem
    
            Return 0
        End Function
    
    End Module
  2. Save the file

Period: .

After declaring the variable and allocating memory for it, the compiler reserves enough memory to accommodate all the members of the class and those members become available to you.

To access the member of a class, type the name of the variable, followed by a period, followed by the name of the member you want. The member you are trying to use must be part of the class. Here is an example:

Module Exercise
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        Dim Recto As Rectangle

        Recto.Length

        Return 0
    End Function

End Module

If you are using either Microsoft Visual Basic or another editor equipped with Intellisense, after you type the period, the list of members would appear:

Intellisense

If you know the name of the member, you can start typing it:

  • Once the desired member is highlighted, press the Space bar or Tab
  • If you see the name of the member in the list, you can double-click click it
  • If the list doesn't appear, press Ctrl + Space bar

If you don't want to use the list displayed by the Code Editor, press Esc. Once you have specified what member you want to use, you can assign it the desired value. Here is an example:

Module Exercise
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        Dim Recto As Rectangle

        Recto.Length = 24.55
       
        Return 0
    End Function

End Module

In the same way, you can access all the desired members of a class and initialize them to complete the variable. By default, each member variable must be initialized on its own line. Here are examples:

Module Exercise
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        Dim Recto As Rectangle

        Recto.Length = 24.55
        Recto.Height = 20.75
       
        Return 0
    End Function

End Module

You may remember that in Lesson 2, we saw that you can use the colon operator to create more than one statement on the same line. In the same way, you can use it to initialize many member variables on the same line as long as you separate them with an empty space, a colon, and another empty. Here is an example:

Module Exercise
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        Dim Recto As Rectangle

        Recto.Length = 24.55 : Recto.Height = 20.75
       
        Return 0
    End Function

End Module

As done so far, after declaring the variable, allocating memory for it, and initializing its member variables, you can use the object as you see fit. For example, you can display the values of the object by accessing each one of its member member variables. Here are examples:

Module Exercise
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        Dim Recto As Rectangle

        Recto = New Rectangle
        Recto.Length = 24.55 : Recto.Height = 20.75

        MsgBox("=-= Rectangle Characteristics =-=" & vbCrLf & _
               "Length: " & vbTab & Recto.Length & vbCrLf & _
               "Height: " & vbTab & Recto.Height)
        Return 0
    End Function

End Module

This would produce:

Using a Class

You can also request the values of the members of a class from the user. Here is an example:

Module Exercise
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        Dim Recto As Rectangle

        Recto = New Rectangle
        Recto.Length = InputBox("Enter Rectangle Length: ")
        Recto.Height = InputBox("Enter Rectangle Height: ")

        MsgBox("=-= Rectangle Characteristics =-=" & vbCrLf & _
               "Length: " & vbTab & Recto.Length & vbCrLf & _
               "Height: " & vbTab & Recto.Height)
        Return 0
    End Function

End Module

You can also involve the members of a class in any operation you see fit, even if the other operands are locally declared variables or constant values as in the following code:

Module Exercise
    Private Class Rectangle
        Public Length As Double
        Friend Height As Double
    End Class

    Public Function Main() As Integer
        Dim Recto As Rectangle
        Dim Perimeter As Double
        Dim Area As Double

        Recto = New Rectangle
        Recto.Length = InputBox("Enter Rectangle Length: ")
        Recto.Height = InputBox("Enter Rectangle Height: ")

        Perimeter = (Recto.Length + Recto.Height) * 2
        Area = Recto.Length * Recto.Height

        MsgBox("=-= Rectangle Characteristics =-=" & vbCrLf & _
               "Length: " & vbTab & vbTab & Recto.Length & vbCrLf & _
               "Height: " & vbTab & vbTab & Recto.Height & vbCrLf & _
               "Perimeter: " & vbTab & Perimeter & vbCrLf & _
               "Area: " & vbTab & vbTab & Area)
        Return 0
    End Function

End Module

Here is an example of running the program:

Using a Class

Practical LearningPractical Learning: Using an Object

  1. To use a DepartmentStore object, change the Program.vb file as follows:
     
    Public Module DepartmentStore
    
        Public Function Main() As Integer
            Dim dptStore As StoreItem
    
            dptStore = New StoreItem
    
            dptStore.ItemNumber = 437876
            dptStore.ItemName = "Crinkled Georgette Dress"
            dptStore.UnitPrice = 42.95
    
            MsgBox("=-= Department Store =-=" & vbCrLf & _
                   "Item #:" & vbTab & vbTab & dptStore.ItemNumber & vbCrLf & _
                   "Item Name:" & vbTab & dptStore.ItemName & vbCrLf & _
                   "Unit Price: " & vbTab & FormatCurrency(dptStore.UnitPrice), _
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Department Store")
            Return 0
        End Function
    
    End Module
  2. Execute the application to test it. This would produce:
     
    Department Store 
  3. Click OK and return to your programming environment

With a Class Instance

After declaring a variable of a class, you can initialize it and access any of its members as you see fit. To initialize an object of a class, we saw that you can access any or each of its friend and public member variables and assign each the appropriate value. Here is an example:

Module Exercise
    Private Enum EmploymentStatus
        esPartTime
        esFullTime
        esContractor
    End Enum

    Private Class Employee
        Public FirstName As String
        Public LastName As String
        Public Address As String
        Public City As String
        Public State As String
        Public ZIPCode As Long
        Public Gender As Char
        Public EmplStatus As EmploymentStatus
    End Class

    Public Function Main() As Integer
        Dim Empl As New Employee

        Empl.FirstName = "Emilie"
        Empl.LastName = "Gudson"

        MsgBox("Employee Information" & vbCrLf & _
               "Full Name: " & Empl.LastName & ", " & Empl.FirstName)
        Return 0
    End Function

End Module

This would produce:

With

If a class has many members and you want to change the values of many or all of them, start a section using the With keyword followed by the name of the variable. Create a new line and type End With. Here is an example:

Public Function Main() As Integer
    Dim StaffMember As New Employee

    With StaffMember

    End With
        
    Return 0
End Function

The section between the With Variable line and the End With line is the body of the With statement. In that body, to access a member variable, type the period operator followed by the desired member. You can then initialize the member variable. Here is an example:

Module Exercise

    Enum EmploymentStatus
        esPartTime
        esFullTime
        esContractor
    End Enum

    Class Employee
        Public FirstName As String
        Public LastName As String
        Public Address As String
        Public City As String
        Public State As String
        Public ZIPCode As Long
        Public Gender As Char
        Public EmplStatus As EmploymentStatus
    End Class

    Sub Main()
        Dim Empl As New Employee

        With Empl
            .FirstName = "Emilie"
            .LastName = "Gudson"
            .Address = "824 Lauseanne Ave"
            .City = "Takoma Park"
            .State = "Maryland"
            .ZIPCode = 20910
            .Gender = "F"
            .EmplStatus = EmploymentStatus.esFullTime
        End With

        msgbox()
    End Sub

End Module

In that same section, you can access each desired member and involve it in an expression or display its value, all of that without indicating the class variable. Here is an example:

Module Exercise
    Private Enum EmploymentStatus
        esPartTime
        esFullTime
        esContractor
    End Enum

    Private Class Employee
        Public FirstName As String
        Public LastName As String
        Public Address As String
        Public City As String
        Public State As String
        Public ZIPCode As Long
        Public Gender As Char
        Public EmplStatus As EmploymentStatus
    End Class

    Public Function Main() As Integer
        Dim StaffMember As New Employee
        Dim Summary As String

        Dim Empl As New Employee

        With StaffMember
            .FirstName = "Emilie"
            .LastName = "Gudson"
            .Address = "824 Lauseanne Ave"
            .City = "Takoma Park"
            .State = "Maryland"
            .ZIPCode = 20910
            .Gender = "F"
            .EmplStatus = EmploymentStatus.esFullTime

            Summary = "Employee Information" & vbCrLf & _
                   "Full Name:" & vbTab & .LastName & ", " & .FirstName & vbCrLf & _
                   "Address:" & vbTab & vbTab & .Address & vbCrLf & _
                   vbTab & vbTab & .City & ", " & .State & " " & .ZIPCode & vbCrLf & _
                   "Gender"

            If .Gender = "M" Then
                Summary &= "" & vbTab & vbTab & "Male" & vbCrLf
            ElseIf .Gender = "F" Then
                Summary &= "" & vbTab & vbTab & "Female" & vbCrLf
            Else
                Summary &= "" & vbTab & vbTab & "Unknown" & vbCrLf
            End If

            Summary &= "Employment: "
            If .EmplStatus = EmploymentStatus.esContractor Then
                Summary &= "" & vbTab & "Contractor"
            ElseIf .EmplStatus = EmploymentStatus.esFullTime Then
                Summary &= "" & vbTab & "Full Time"
            Else
                Summary &= "" & vbTab & "Part Time"
            End If

            MsgBox(Summary)
        End With
        Return 0
    End Function

End Module

This would produce:

With

Practical LearningPractical Learning: Using an Object With...

  1. To use the With operator, change the code as follows:
     
    Public Module DepartmentStore
    
        Public Function Main() As Integer
            Dim dptStore As StoreItem
    
            dptStore = New StoreItem
    
            With dptStore
                .ItemNumber = 437876
                .ItemName = "Crinkled Georgette Dress"
                .UnitPrice = 42.95
    
                MsgBox("=-= Department Store =-=" & vbCrLf & _
                       "Item #:" & vbTab & vbTab & .ItemNumber & vbCrLf & _
                       "Item Name:" & vbTab & .ItemName & vbCrLf & _
                       "Unit Price: " & vbTab & FormatCurrency(.UnitPrice), _
                       MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _
    			"Department Store")
            End With
    
            Return 0
        End Function
    
    End Module
  2. Execute the application to test it 
  3. Click OK and return to your programming environment

Class Members and Access Modifiers

 

The Friend Member Variables of a Class

In our introduction to member variables of a class, we saw that they could be made friend or public. Here is an example:

Private Class Cylinder
    Friend Radius As Double
End Class

The Private Member Variables of a Class

A member variable can also be made private. A member is private if it can be accessed only by other members of the same class. Other classes from the same module, the same file, the same project or outside of the project, cannot access such a member variable.

To declare a private member variable, precede it with the Private keyword. Here is an example:

Private Class Cylinder
    Friend Radius As Double
    Private Height As Double
End Class

As mentioned already, the private member variable is available to the methods of the same class and those methods can use it as they see fit. Here is an example

Private Class Cylinder
    Friend Radius As Double
    Private Height As Double

    Sub Show()
         MsgBox("=-= Cylinder Characteristics =-=" & vbCrLf & _
                "Radius: " & vbTab & Radius & vbCrLf & _
                "Height: " & vbTab & Height)
    End Sub
End Class
 

Home Copyright © 2008-2016, FunctionX, Inc.