![]() |
Introduction to Classes |
In previous lessons, we used individual variables whenever we needed them. This allowed us to declare simple types to hold fairly small values. 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.
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: 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:
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 Basic:
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.
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
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. 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
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
|
||||||||||||||||||||||||||||||||||||||||||||
|
|
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
|
|
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 Visual Basic easier, many classes were created and stored in various namespaces. Each namespace is used to provide specific instructions. The most regularly used namespace in Visual Basic 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.
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.
Imports System
Module Exercise
Sub Main()
Console.WriteLine("Welcome to the Wonderful World of VBasic")
End Sub
End Module
|
|
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 Visual Basic applications. As mentioned earlier, you may have it already installed in your computer. Otherwise, you can download it from the Microsoft web site.
![]() |
The Methods of a Class |
The variables of a program cannot perform assignments. In the same way, the member variables of a class can initiate nor perform actions. So far, we were using procedures to do that. In the same way, to create a class as complete as possible, you can equip it with its own procedures. Such a procedure is created as a member of the class. A procedure that is made a member of a class is also called a method. Throughout these lessons, the word method will be used as a procedure (Sub or Function) that is a member of a class.
Like a normal procedure, a method can be made to return a value, in which case it would be a function. To create a method as a function, use the same techniques we have used so far to create a function. Here is an example: Imports System
Module Exercise
Class TRectangle
Public Length As Double
Public Height As Double
Function Perimeter() As Double
End Function
End Class
Sub Main()
End Sub
End Module
A method can also be created not to return a value, making a sub procedure. After declaring a procedure, in its body, you can implement the expected behavior. When a method has been created, it has access to all of the other members of the same class. This means that you don't have to re-declare a member of a class to access it in a method. Based on this, you can manipulate any member variable of the same class as you wish. Like the member variables, the methods can be accessed outside of the class using the period operator. Here is an example: Imports System
Module Exercise
Class TRectangle
Public Length As Double
Public Height As Double
Function Perimeter() As Double
Return (Length + Height) * 2
End Function
Function Area#()
Return Length * Height
End Function
End Class
Sub Main()
Dim 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
Console.WriteLine()
Console.WriteLine("Rectangle Characteristics")
Console.WriteLine("Length: {0}", Recto.Length)
Console.WriteLine("Height: {0}", Recto.Height)
Console.WriteLine("Perimeter: {0}", Recto.Perimeter)
Console.WriteLine("Area: {0}", Recto.Area)
Console.WriteLine()
End Sub
End Module
|
|
Methods and Arguments |
|
Like regular procedures we have used so far, methods of a class can have arguments. The rules are the same as we have applied them so far. When you create a method, it has direct access to all regular members of its class. This means that you don't have to create an argument for a member variable of the same class. You would need an argument only if an external value would be passed to the method. |
|
|
|
|
Methods Overloading |
|
Just done for regular procedures, the methods of a class can be overloaded. The difference between two overloaded methods must lie on their signature which includes the names of the methods, their arguments, and the numbers of their arguments. |
![]() |
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 public member variables and assign it the appropriate value. Here is an example: Imports System
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
Empl.FirstName = "Emilie"
Empl.LastName = "Gudson"
Console.WriteLine("Employee Information")
Console.WriteLine("Full Name: {0}, {1}", Empl.LastName, Empl.FirstName)
Console.WriteLine()
End Sub
End Module
This would produce: Employee Information Full Name: Gudson, Emilie If a class has many members and you want to change the values of many or all of them, you can use the With keyword to type the name of the class variable once. After doing this, use the period operator to access each desired member. Here is an example: Imports System
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
Console.WriteLine("Employee Information")
Console.WriteLine("Full Name: {0}, {1}", .LastName, .FirstName)
Console.WriteLine("Address: {0}", .Address)
Console.WriteLine(" {0}, {1}, {2}", .City, .State, .ZIPCode)
Console.Write("Gender: ")
If .Gender = "M" Then
Console.WriteLine("Gender")
ElseIf .Gender = "F" Then
Console.WriteLine("Female")
Else
Console.WriteLine("Unknown")
End If
Console.Write("Empl Status: ")
If .EmplStatus = EmploymentStatus.esContractor Then
Console.WriteLine("Contractor")
ElseIf .EmplStatus = EmploymentStatus.esFullTime Then
Console.WriteLine("Full Time")
Else
Console.WriteLine("Part Time")
End If
End With
Console.WriteLine()
End Sub
End Module
This would produce: Employee Information
Full Name: Gudson, Emilie
Address: 824 Lauseanne Ave
Takoma Park, Maryland, 20910
Gender: Female
Empl Status: Full Time
|
|
Shared Member Variables |
|
Shared Methods |
|
Consider the following class: Imports System
Module Exercise
Class TRectangle
Public Length As Double
Public Shared Height As Double
Function Perimeter#()
Return (Length + Height) * 2
End Function
Function Area#()
Return Length * Height
End Function
End Class
Sub Main()
REM Notice that a TRectangle variable is not declared
TRectangle.Height = 20.68
TRectangle.Length = 32.47
Console.WriteLine("Rectangle Characteristics")
Console.WriteLine("Length: {0}", TRectangle.Length)
Console.WriteLine("Height: {0}", TRectangle.Height)
End Sub
End Module
This would produce: Rectangle Characteristics Length: 32.47 Height: 20.68 Like member variables, a method can be shared among classes. In some cases, shared methods are more used than shared member variables because a shared method allows performing an action on a class without declaring an instance of that class. To create a shared method, type the Shared keyword on the left of the method's name. Like a shared member variable, once a method has been created as shared, it can be accessed directly from anywhere. Remember that you would need to type the name of the class before accessing the method. The name of the class allows you to "qualify" the method. Here is an example: Imports System
Module Exercise
Class TRectangle
Public Shared Length As Double
Public Shared Height As Double
Shared Function Perimeter#()
Return (Length + Height) * 2
End Function
Shared Function Area#()
Return Length * Height
End Function
End Class
Sub Main()
REM Notice that a TRectangle variable is not declared
TRectangle.Height = 20.68
TRectangle.Length = 32.47
Console.WriteLine("Rectangle Characteristics")
Console.WriteLine("Length: {0}", TRectangle.Length)
Console.WriteLine("Height: {0}", TRectangle.Height)
Console.WriteLine("Perimeter: {0}", TRectangle.Perimeter)
Console.WriteLine("Area: {0}", TRectangle.Area)
End Sub
End Module
|
|
Sharing the Main Method |
|
So far, we were creating the Main() procedure as a Sub. This was a requirement for it when belonging to a module. If you want to create your application from a class, you can include the Main() procedure in such a class. The rule you must observe is that Main() must be created as a shared procedure. Based on this, you can create Main() as follows: Imports System
Class Exercise
Shared Sub Main()
Console.WriteLine("Microsoft Visual Basic .NET Programming Language")
End Sub
End Class
For the rest of our lessons, we will use either the module or the class version. |
|
We have mentioned two techniques of accessing the members of a class, one consisted of declaring a variable of the class, the other had to do with Shared members. None of these techniques is important if you want to access a member variable or method of a class from another method of the same class. We know already that the members of a class are made available to all other members of the same class without being declared or qualified. Consider the following class: Public Class Triangle
Public Base As Double
Public Height As Double
Public Area As Double
Public Sub Show()
Dim Area As Double
Area = Base * Height / 2
End Sub
End Class
When the Area variable is used in the Show() method, there are two variables available and named Area. It makes it confusing to know what particular variable is being accessed. You can use a special member of a class that allows you to specify the member of a class when accessing it. This member is called Me. When using Me, you can access any member of a class within any method of the same class. Here is an example: Imports System
Class Exercise
Public Class Triangle
Public Base As Double
Public Height As Double
Public Sub Show()
Dim Area As Double
' Using "this" to access the members of this class
Me.Base = 24.55
Me.Height = 20.75
' You cannot use this to access Area because Area
' is not a member of this class
Area = Me.Base * Me.Height / 2
Console.WriteLine("Triangle Characteristics")
Console.WriteLine("Base: {0}", Me.Base)
Console.WriteLine("Height: {0}", Me.Height)
Console.WriteLine("Area: {0}", Area) ' Area is not a member of the Exercise class
End Sub
End Class
Shared Sub Main()
Dim tri As Triangle = New Triangle
tri.Show()
End Sub
End Class
This would produce: Triangle Characteristics Base: 24.55 Height: 20.75 Area: 254.70625 There are exceptions when using Me:
|
|
|
||
| Previous | Copyright © 2008 Yevol | Next |
|
|
||