Home

Introduction to Classes

 

Programmer-Defined Types

 

Introduction

In previous lessons, we used individual variables whenever we needed them. This allowed us to declare simple types to hold fairly small values. In VBasic, 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 Notepad
  2. In the empty file, type the following:
     
    Imports System
    
    Module Exercise
    
        Sub Main()
        
        End Sub
    
    End Module
  3. To save the file, on the main menu click File -> Save
  4. Locate your VBasic folder and display it in the Save In combo box
  5. Click the Create New Folder button on the toolbar of the Save As dialog box
  6. Type DeptStore1 as the name of the new folder and press Enter twice to display it in the Save In combo box
  7. Change the Save As Type combo box to All Files
  8. Set the name of the file to Exercise.vb and click Save
 

Creating a Class

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

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

Imports System

Module Exercise

    Sub Main()
        Dim RectLength As Double
        Dim RectHeight As Double

        RectLength = 24.55 : RectHeight = 20.75

        Console.WriteLine("=-= Rectangle Characteristics =-=")
        Console.WriteLine("Length:    {0}", RectLength)
        Console.WriteLine("Height:    {0}", RectHeight)

        Console.WriteLine()
    End Sub

End Module

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 TRactangle;

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 TRectangle

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 TRectangle
    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 TRectangle
    Length As Double
    Height As Double
End Class
 

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:

Stock #: 437876
Women Spring Coat Classy
Unit: $145.55
Stock #: 79475
Women Bathing Suit Sandstone
$75.55
Stock #: 74797
Women Suit Exchange
$225.75
Stock: 68432
Men Jacket
$115.85
Stock #: 75947
Children Summer Hat
$17.95
Stock #: 48746
Children Playground Dress
$24.55

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. In the document, create a DepartmentStore class as follows:
     
    Imports System
    
    Module Exercise
    
        Class DepartmentStore
            Dim ItemNumber As Long
            Dim ItemName As String
            Dim UnitPrice As Double
        End Class
    
        Sub Main()
        
        End Sub
    
    End Module
  2. Save the file

Accessing a Class

A common object in real life is visibly made of two categories of parts: those you can see or touch and those you do not have access to. The parts you can see or touch are considered visible or accessible. A parts that is visible is referred to as public. A part you cannot see or touch are considered hidden, also referred to as private. Like objects in real life, a class is made of members that the other parts of a program cannot “see” and those the other parts of a program can access. The other parts of a program are sometimes referred to as clients. The parts a client can see in a class are considered public and the others are private.

When creating a class, you will define what members are public and which ones are private. The members that are public are preceded by Public keyword. The others are preceded by the Private keyword. If you don't specify an access level of a member of a class, the member is considered private. Based on this, both members of the TRectangle class created above are private. To make them public, the class can be created as follows:

Class TRectangle
    Public Length As Double
    Public Height As Double
End Class

The public and private keywords are referenced by their access level because they control how much access a variable allows. 

HomePractical Learning: Controlling the Access Level

  1. To specify the member variables as public, change the file as follows:
     
    Imports System
    
    Module Exercise
    
        Class DepartmentStore
            Public ItemNumber As Long
            Public ItemName As String
            Public UnitPrice As Double
        End Class
    
        Sub Main()
            
        End Sub
    
    End Module
  2. Save the file 

Sharing a Class

Although you may think of working only in Visual Basic .NET, in some cases, you may create a class and need 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 TRectangle
    Length As Double
    Height As Double
End Class

A Program With Various Files

Instead of only one file, you can create a program with many of them. Each file can contain different assignments that, when put together, can create an application as complete as possible. To make this possible, you can create each file with a name and the extension .vb. To compile the project, after typing vbc, you can list the files separated by commas.

 

Declaring a Variable of a Class

After creating a class, to use it in a program, you can declare it as a variable. Unlike variables declared from primitive types as we have done so far, a class must be declared as a reference. This is done by assigning the New keyword followed by the name of the class to the declared variable. For example, do declare a variable of the above TRectangle class, you would type the following:

Imports System

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Height As Double
    End Class

    Sub Main()
        Dim Recto As New TRectangle

    End Sub

End Module

Period: .

To access the property of an object, type the name of the object, followed by a period, followed by the name of the property you need. The property you are trying to use must be part of the properties of the object.

If you know the name of the property, you can start typing it. Once the desired property is highlighted, press the Space bar or Tab. If you see the name of the property 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 property you want to use, you can assign it the desired value or you can involve it in any operation you see fit.

A variable declared of a class is also called an object. When an object has been created, you can access any of its members using the period operator ".". First, type the name of the object, followed by a period, followed by the name of the member you want to access. For example, to access the Length member of the above class, you would write:

Recto.Length

Using this syntax, you can display the value of a class member. Here are examples:

Imports System

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Height As Double
    End Class

    Sub Main()
        Dim Recto As New TRectangle

        Recto.Length = 24.55 : Recto.Height = 20.75

        Console.WriteLine("=-= Rectangle Characteristics =-=")
        Console.WriteLine("Length:    {0}", Recto.Length)
        Console.WriteLine("Height:    {0}", Recto.Height)

        Console.WriteLine()
    End Sub

End Module

Here is an example of running the program:

=-= Rectangle Characteristics =-=
Length:    24.55
Height:    20.75

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

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Height As Double
    End Class

    Sub Main()
        Dim Recto As New TRectangle

        Console.Write("Enter Rectangle Length: ")
        Recto.Length = Console.ReadLine()
        Console.Write("Enter Rectangle Height: ")
        Recto.Height = Console.ReadLine

        Console.WriteLine()
        Console.WriteLine("=-= Rectangle Characteristics =-=")
        Console.WriteLine("Length:    {0}", Recto.Length)
        Console.WriteLine("Height:    {0}", Recto.Height)

        Console.WriteLine()
    End Sub

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:

Imports System

Module Exercise

    Class TRectangle
        Public Length As Double
        Public Height As Double
    End Class

    Sub Main()
        im Recto As New TRectangle
        Dim Perimeter As Double
        Dim Area As Double


        Console.Write("Enter Rectangle Length: ")
        Recto.Length = Console.ReadLine()
        Console.Write("Enter Rectangle Height: ")
        Recto.Height = Console.ReadLine

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

        Console.WriteLine()
        Console.WriteLine("Rectangle Characteristics")
        Console.WriteLine("Length:    {0}", Recto.Length)
        Console.WriteLine("Height:    {0}", Recto.Height)
        Console.WriteLine("Perimeter: {0}", Perimeter)
        Console.WriteLine("Area:      {0}", Area)

        Console.WriteLine()
    End Sub

End Module

Here is an example of running the program:

Enter Rectangle Length: 32.48
Enter Rectangle Height: 28.64

Rectangle Characteristics
Length:    32.48
Height:    28.64
Perimeter: 122.24
Area:      930.2272

 

 

Practical LearningPractical Learning: Declaring a Class Variable

  1. To use the DepartmentStore class in the main class of the project, change the file as follows:
     
    Imports System
    
    Module Exercise
    
        Public Class DepartmentStore
            Public ItemNumber As Long
            Public ItemName As String
            Public UnitPrice As Double
        End Class
    
        Sub Main()
            Dim dptStore As DepartmentStore = New DepartmentStore
    
            dptStore.ItemNumber = 737853
            dptStore.ItemName = "Men's Tie"
            dptStore.UnitPrice = 35.95
    
            Console.WriteLine("Department Store")
            Console.WriteLine("Item #:     {0}", dptStore.ItemNumber)
            Console.WriteLine("Item Name:  {0}", dptStore.ItemName)
            Console.WriteLine("Unit Price: {0}", dptStore.UnitPrice)
        End Sub
    
    End Module
  2. Save the Exercise.vb file and open the Command Prompt
  3. Switch to the folder that contains the above file
  4. Compile it by typing vbc Exercise.vb and pressing Enter
  5. Execute it by typing Exercise and pressing Enter. This would produce:
     
     
  6. Return to Notepad

 

Namespaces

 

Introduction

A namespace is a section of code that is recognized with a name. Namespaces were created to allow each programmer or a group of programmers who work with others to create code with names that don't conflict with code of the other programmers or other groups. Based on their usefulness, namespaces have become highly used.

Accessing Members of a Namespace

To access an item that is part of the namespace, you can use the period operator. To do this, in the desired location, type the name of the namespace, followed by a period, followed by the desired member of the namespace. For example, if you had a namespace named Accounting and it contains a member named Departure, to access this member, you would type the following:

Accounting.Departure

The System Namespace

To make programming in VBasic easier, many classes were created and stored in various namespaces. Each namespace is used to provide specific instructions. The most regularly used namespace in VBasic is called System. Inside of the System namespace is a class called Console. The Console class is used to display things on the console screen also called the DOS window.

The Console class contains procedures to display information on the screen or to retrieve information from the user who types it in the DOS window. The procedure that is used to display text on the screen is called Write. To use Write(), inside of the parentheses, type the sentence between double-quotes.

Besides Write(), the Console class also provides a procedure called WriteLine(). The difference is that, after displaying something on the screen, the Write() method keeps the caret on the same line but WriteLine() transfers the caret to the next line.

 

Importing a Namespace

We mentioned that, to access a member of a namespace, you could type the name of the namespace, followed by a period, and followed by the name of the member. This technique is referred to as qualifying a member of a namespace. This can be long ins some cases. Instead of qualifying a member of a namespace every time you want to use it, you can import the namespace into the file where you want to access its member(s). To import a namespace, type the Imports keyword in the top section of the file, followed by the name of the namespace.

Practical LearningPractical Learning: Importing a Namespace

  1. Return to Notepad and change the program as follows:
     
    Imports System
    
    Module Exercise
        Sub Main()
            Console.WriteLine("Welcome to the Wonderful World of VBasic")
        End Sub
    End Module
  2. Save the file and return to the Command Prompt
  3. To compile the exercise, type vbc exercise.vb and press Enter
  4. To execute the application, type exercise and press Enter
  5. Return to Notepad

 

Introduction to Libraries

A library is code that can be used by programmers without knowing how the library was created. The only important information about the library is to know what it offers and how its contents can be used to complement a program. Microsoft created a huge library called the .NET Framework. You need this library to create VBasic applications. As mentioned earlier, you may have it already installed in your computer. Otherwise, you can download it from the Microsoft web site.

 

 

Previous Copyright © 2004-2016, FunctionX, Inc. Next