Home

Implementing the Methods of a Class

 

Details on Implementing Methods

 

The Case of Function Methods

So far, we have seen how to create sub procedure in a class, which is a method that does not return a value. 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:

Friend Class Rectangle
    Public Length As Double
    Public Height As Double

    Function Assign() As Double

    End Function
End Class

After declaring a procedure, in its body, you can implement the expected behavior. As seen for a sub procedure, 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. This means that, naturally, you do not have to create a function method to change the value of a member variable. A normal sub procedure can take care of this. Instead, you would create a method if you need to perform a calculation and get a value from it instead of storing that value in one of the member variables. Here is an example:

Friend Class Rectangle
    Public Length As Double
    Public Height As Double

    Function Assign() As Double

    End Function

    Function Perimeter() As Double

    End Function
End Class

Therefore, in the body of the function, you can access a member variable, you can call another method of the same class, or you can use an external value as you see fit. When the function exits, make sure it returns the appropriate value based on its type. Like the member variables, the methods can be accessed outside of the class using the period operator. Here is an example:

Public Module Exercise
    Friend Class Rectangle
        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

    Public Function Main() As Integer
        Dim Recto As Rectangle

        Recto = New Rectangle

        Recto.Length = 42.58 : Recto.Height = 28.08

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

        Return 0
    End Function
End Module

This would produce:

Method

Like a sub procedure that is created as a method, a member function of a class can be made private, public, or friendly. It follows the exact same rules we reviewed early.

Practical LearningPractical Learning: Implementing the Methods of a Class

  1. Start Microsoft Visual Basic and create a Console Application named DepartmentStore2
  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. To add two methods of the class, change the file as follows:
     
    Module DepartmentStore
    
        Public Class StoreItem
            Public ItemNumber As Long
            Public ItemName As String
            Public UnitPrice As Double
    
            Public Sub RegisterStoreItem()
                ItemNumber = CLng(InputBox("=#=  Department Store =#=" & vbCrLf & _
                                      " --- Item Registration ---" & vbCrLf & _
                                      vbCrLf & vbCrLf & vbCrLf & _
                                      "Enter Item #", "Department Store"))
                ItemName = InputBox("=#=  Department Store =#=" & vbCrLf & _
                                      " --- Item Registration ---" & vbCrLf & _
                                      "Enter Item Name", "Department Store")
                UnitPrice = CDbl(InputBox("=#=  Department Store =#=" & vbCrLf & _
                                      " --- Item Registration ---" & vbCrLf & _
                                      vbCrLf & vbCrLf & vbCrLf & _
                                      "Enter Unit Price", "Department Store"))
            End Sub
    
            Public Sub ShowItem()
                MsgBox("=-= Department Store =-=" & vbCrLf & _
                       "---  Store Inventory ---" & vbCrLf & _
                       "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _
                       "Item Name:" & vbTab & ItemName & vbCrLf & _
                       "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _
                       MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _
                       "Department Store")
            End Sub
        End Class
    
        Public Function Main() As Integer
            Dim dptStore As StoreItem = New StoreItem
    
            dptStore.RegisterStoreItem()
            dptStore.ShowItem()
    
            Return 0
        End Function
    
    End Module
  5. Execute the program to test it
  6. Enter the item # as 740797
     
    Department Store
  7. Enter the item name as Pencil Skirt
     
    Department Store
  8. Enter the price as 25.75
     
    Department Store
    Department Store
  9. Close the form and return to your programming environment

Methods and Arguments

Like regular procedures we have used so far, methods 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 as done for regular procedures, a method of a class can be overloaded. To overload a method, create more than one method with the same name. The methods with same names must have different rules in their arguments:

  • They can have different types of arguments. Here is an example:
     
    Private Class EmployeeInformation
        REM Contractor Registration
        Private Sub Register(ByVal SalaryCategory As Integer)
    
        End Sub
    
        REM Full Time Employee Registration
        Private Sub Register(ByVal HourlySalary As Double)
    
        End Sub
    End Class
  • They can have a different number of arguments. Here is an example:
     
    Private Class Geometry
        REM The area of a square
        Friend Function CalculateArea#(ByVal Side#)
            Area# = Side * Side
        End Function
    
        REM The area of a rectangle
        Friend Function CalculateArea#(ByVal Length#, ByVal Height#)
            Area# = Length# * Height#
        End Function
    End Class

Any or both of these two rules must be respected.

The Shared Members of a Class

 

Shared Member Variables

When you declare a variable of a class, you are said to have created an instance of the class. This makes an object available so you can initialize and use its member variables and methods as you see fit. Just as you can declare one instance of a class, in the same way, you can declare as many instances as you judge it necessary. After declaring various variables of the same class and initializing them, each variable has and keeps its own values. Here is an example:

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

        Public Function CalculatePerimeter#()
            Return (Length + Height) * 2
        End Function

        Public Function CalcaulteArea#()
            Return Length * Height
        End Function
    End Class

    Public Function Main() As Integer
        Dim RegistrationCard As New Rectangle
        Dim Invoice As New Rectangle

        RegistrationCard.Length = 24.55 : RegistrationCard.Height = 20.68
        Invoice.Length = 8.5 : Invoice.Height = 11.65

        MsgBox("==========================" & vbCrLf & _
               "=-= Paper Registration Characteristics =-=" & vbCrLf & _
               "Length: " & vbTab & vbTab & RegistrationCard.Length & vbCrLf & _
               "Height: " & vbTab & vbTab & RegistrationCard.Height & vbCrLf & _
               "Perimeter: " & vbTab & _
	       RegistrationCard.CalculatePerimeter#() & vbCrLf & _
               "Area: " & vbTab & vbTab & _
	       RegistrationCard.CalcaulteArea#() & vbCrLf & _
               "----------------------------------------------------" & vbCrLf & _
               "=-= Paper Registration Characteristics =-=" & vbCrLf & _
               "Length: " & vbTab & vbTab & Invoice.Length & vbCrLf & _
               "Height: " & vbTab & vbTab & Invoice.Height & vbCrLf & _
               "Perimeter: " & vbTab & Invoice.CalculatePerimeter#() & vbCrLf & _
               "Area: " & vbTab & vbTab & Invoice.CalcaulteArea#() & vbCrLf & _
               "==========================")
        Return 0
    End Function

End Module

This would produce:

Introduction to Shared Members

In order to access the member variables of the above Rectangle class, you must declare a variable of the class. The Visual Basic language provides an alternative. You can declare a member variable so that you can access it from anywhere in your code without primarily declaring a variable of the class. In order to have such a member variable, you must explicitly create it as shared.

To create a shared member variable, type the Shared keyword on its left when declaring it. After the shared member variable has been declared, you can use it like any other member variable of that class, except that you don't need to declare an instance of that class when you want to access that member variable. Here is an example:

Public Module Exercise
    Friend Class Rectangle
        Public Length As Double
        Public Shared Height As Double

        Public Function CalculatePerimeter#()
            Return (Length + Height) * 2
        End Function

        Public Function CalcaulteArea#()
            Return Length * Height
        End Function
    End Class

    Public Function Main() As Integer
        REM Notice that a Rectangle variable is not declared
        Rectangle.Height = 20.68

        MsgBox("Rectangle Characteristics" & vbCrLf & _
               "Height:" & vbTab & vbTab & Rectangle.Height)

        Return 0
    End Function
End Module

This would produce:

A Shared Member Variable

Based on this, when creating a class, you will decide whether you want a particular member variable to be shared or not. You can have only one, two, more, or all member variables shared in a class. Experience and your own goal will guide you.

Shared Methods

Consider the following class:

Public Module Exercise
    Friend Class Rectangle
        Public Shared Length As Double
        Public Shared Height As Double

        Public Function CalculatePerimeter#()
            Return (Length + Height) * 2
        End Function

        Public Function CalcaulteArea#()
            Return Length * Height
        End Function
    End Class

    Public Function Main() As Integer
        REM Notice that a Rectangle variable is not declared
        Rectangle.Height = 20.68
        Rectangle.Length = 32.47

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

End Module

This would produce:

Shared

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 Sub or the Function keyword. Here is an example:

Here is an example:

Friend Class Rectangle
    Shared Function CalculatePerimeter#()
        Return (Length + Height) * 2
    End Function
End Class

You can apply the access modifier on the method as we have done so far. Here are examples:

Friend Class Rectangle
    Public Shared Function CalculatePerimeter#()

    End Function

    Public Shared Function CalcaulteArea#()

    End Function
End Class

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:

Public Module Exercise
    Friend Class Rectangle
        Public Shared Length As Double
        Public Shared Height As Double

        Public Shared Function CalculatePerimeter#()
            Return (Length + Height) * 2
        End Function

        Public Shared Function CalcaulteArea#()
            Return Length * Height
        End Function
    End Class

    Public Function Main() As Integer
        REM Notice that a Rectangle variable is not declared
        Rectangle.Height = 20.68
        Rectangle.Length = 32.47

        MsgBox("Rectangle Characteristics" & vbCrLf & _
               "Length:" & vbTab & vbTab & Rectangle.Length & vbCrLf & _
               "Height:" & vbTab & vbTab & Rectangle.Height & vbCrLf & _
               "Perimeter: " & vbTab & Rectangle.CalculatePerimeter#() & vbCrLf & _
               "Area: " & vbTab & vbTab & Rectangle.CalcaulteArea#())
        Return 0
    End Function

End Module

Me

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. 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 Display()
            Dim Area As Double
            Area = Base * Height / 2
        End Sub
End Class

When the Area variable is used in the Display() 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:

Public Module Exercise
    Public Class Triangle
        Public Base As Double
        Public Height As Double
        Public Area As Double

        Public Sub Display()
            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

            MsgBox("Triangle Characteristics" & vbCrLf & _
                   "Base:" & vbTab & Me.Base & vbCrLf & _
                   "Height:" & vbTab & Me.Height & vbCrLf & _
                   "Area: " & vbTab & Area) ' Area is not a member of the Exercise class
        End Sub
    End Class

    Public Function Main() As Integer
        Dim tri As Triangle = New Triangle
        tri.Display()
        Return 0
    End Function

End Module

This would produce:

Me

There are rules you must follow when using Me:

  • Me can never be declared: it is automatically implied when you create a class
  • Me cannot be used in a class A to access a member of class B 
  • Me cannot be used in a Shared method. The following program will not compile because Me is used in the Display() method declared as a Shared method:
     
    Public Class Triangle
        Public Base As Double
        Public Height As Double
        Public Area As Double
    
        Public Shared Sub Display()
            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
    
            MsgBox("Triangle Characteristics" & vbCrLf & _
                   "Base:" & vbTab & Me.Base & vbCrLf & _
                   "Height:" & vbTab & Me.Height & vbCrLf & _
                   "Area: " & vbTab & Area)
        End Sub
    End Class
 

Techniques of Initializing a Member Variable

 

Introduction

In Lesson 2, we saw that when you declare a variable, the compiler initializes its allocated memory with a default value. Consider the following program:

Public Module Exercise
    Private Class Square

        Private Side As Double

        Function CalculatePerimeter() As Double
            Return Side * 4
        End Function

        Function CalculateArea() As Double
            Return Side * Side
        End Function

        Public Sub ShowMessage()
            MsgBox("Square Characteristics" & vbCrLf & _
                   "Side:" & vbTab & vbTab & FormatNumber(Side) & vbCrLf & _
                   "Perimeter:" & vbTab & _
                   FormatNumber(CalculatePerimeter()) & vbCrLf & _
                   "Area:" & vbTab & vbTab & FormatNumber(CalculateArea()))
        End Sub
    End Class

    Public Function Main() As Integer
        Dim sqr As Square = New Square

        sqr.ShowMessage()

        Return 0
    End Function
End Module

This would produce:

Class

Notice that this program indicates that the Side member variable of the Square class was initialized with 0. This means that, like the regular variables, the member variables of a class are initialized by the compiler with default values that depend on the type of the variable. For example, a numeric member variable is initialized with 0 while a string-based variable is initialized with an empty string.

After adding a member variable to a class, instead of relying on the default value assigned by the compiler, you can initialized it with a value of your choice, depending on the type of the variable. You have various alternatives.

Practical LearningPractical Learning: Creating a Class

  1. Create a Console Application named DepartmentStore3
  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. To create a new class, in the Solution Explorer, right-click DepartmentStore3 -> Add -> Class...
  5. Set the Name to StoreItem and press Enter
  6. Change the file as follows:
     
    Public Enum ItemCategory
        Women
        Men
        Girls
        Boys
        Babies
        Jewelry
        Beauty
        Bedroom
        Miscellaneous
    End Enum
    
    Public Class StoreItem
        Friend ItemNumber As Long
        Friend Category As ItemCategory
        Friend ItemName As String
        Friend UnitPrice As Double
    
        Public Sub ShowItem()
            Dim StrCategory As String
    
            Select Case Category
                Case ItemCategory.Women
                    StrCategory = "Women"
                Case ItemCategory.Men
                    StrCategory = "Men"
                Case ItemCategory.Girls
                    StrCategory = "Girls"
                Case ItemCategory.Boys
                    StrCategory = "Boys"
                Case ItemCategory.Babies
                    StrCategory = "Babies"
                Case ItemCategory.Jewelry
                    StrCategory = "Jewelry"
                Case ItemCategory.Beauty
                    StrCategory = "Beauty"
                Case ItemCategory.Bedroom
                    StrCategory = "Bedroom"
                Case Else
                    StrCategory = "Miscellaneous"
            End Select
    
            MsgBox("=-= Department Store =-=" & vbCrLf & _
                   "---  Store Inventory ---" & vbCrLf & _
                   "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _
                   "Category:" & vbTab & StrCategory & vbCrLf & _
                   "Item Name:" & vbTab & ItemName & vbCrLf & _
                   "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _
                   "Department Store")
        End Sub
    End Class
  7. Save All 

Initialization of a Member Variable

One way you can initialize a member variable is to assign it the desired value when declaring it. Here is an example:

Public Module Exercise
    Private Class Square
        Private Side As Double = 48.25

        Function CalculatePerimeter() As Double
            Return Side * 4
        End Function

        Function CalculateArea() As Double
            Return Side * Side
        End Function

        Public Sub Message()
            MsgBox("Square Characteristics" & vbCrLf & _
                   "Side:" & vbTab & vbTab & FormatNumber(Side) & vbCrLf & _
                   "Perimeter:" & vbTab & _
                   FormatNumber(CalculatePerimeter()) & vbCrLf & _
                   "Area:" & vbTab & vbTab & FormatNumber(CalculateArea()))
        End Sub
    End Class

    Public Function Main() As Integer
        Dim sqr As Square = New Square

        sqr.Message()

        Return 0
    End Function
End Module

This would produce:

Class

Notice that, this time, the default value assigned to the member variable applies. Instead of initializing a member variable when declaring it, you can create a method that would be used to do this. Here is an example:

Public Class Square
    Private side As Double

    Public Sub SetSide()
        side = 48.25
    End Sub
End Class

Such a method can also be used to initialize more than one value. When you create a method used to initialize one or more member variables of a class, if you want the initialization to apply, you must make sure that you call that method first before calling other methods of the class.

Just as you can create a method to initialize the member(s) of a class, you can overload that method with different versions to perform different initializations. Here are examples:

Public Module Exercise
    Private Class Square
        Private side As Double

        Public Sub SetSide()
            side = 48.25
        End Sub

        Public Sub SetSide(ByVal sd As Double)
            side = sd
        End Sub

        Function CalculatePerimeter() As Double
            Return Side * 4
        End Function

        Function CalculateArea() As Double
            Return Side * Side
        End Function

        Public Sub Message()
            MsgBox("Square Characteristics" & vbCrLf & _
                   "Side:" & vbTab & vbTab & FormatNumber(Side) & vbCrLf & _
                   "Perimeter:" & vbTab & _
                   FormatNumber(CalculatePerimeter()) & vbCrLf & _
                   "Area:" & vbTab & vbTab & FormatNumber(CalculateArea()))
        End Sub
    End Class

    Public Function Main() As Integer
        Dim sqr As Square = New Square

        sqr.SetSide()
        sqr.Message()

        Dim sd As Double

        sd = CDbl(InputBox("Enter Square Side: "))
        sqr.SetSide(sd)

        sqr.Message()

        Return 0
    End Function
End Module

Here an example of running the program:

Class

Class

Class

Notice that, although the Square.Side member variable is private, you cab call the SetSide() public method to initialize it before displaying the characteristics of a square.

 

Practical LearningPractical Learning: Initializing the Member Variables of a Class

  1. Change the StoreItem class as follows:
     
    Public Enum ItemCategory
        Women
        Men
        Girls
        Boys
        Babies
        Jewelry
        Beauty
        Bedroom
        Miscellaneous
    End Enum
    
    Public Class StoreItem
        Friend ItemNumber As Long
        Friend Category As ItemCategory
        Friend ItemName As String
        Friend UnitPrice As Double
    
        Public Sub Initialize(ByVal Number As Long, _
                              ByVal Type As ItemCategory, _
                              ByVal Name As String, _
                              ByVal Price As Double)
            ItemNumber = Number
            Category = Type
            ItemName = Name
            UnitPrice = Price
        End Sub
    
        Public Sub ShowItem()
            Dim StrCategory As String
    
            Select Case Category
                Case ItemCategory.Women
                    StrCategory = "Women"
                Case ItemCategory.Men
                    StrCategory = "Men"
                Case ItemCategory.Girls
                    StrCategory = "Girls"
                Case ItemCategory.Boys
                    StrCategory = "Boys"
                Case ItemCategory.Babies
                    StrCategory = "Babies"
                Case ItemCategory.Jewelry
                    StrCategory = "Jewelry"
                Case ItemCategory.Beauty
                    StrCategory = "Beauty"
                Case ItemCategory.Bedroom
                    StrCategory = "Bedroom"
                Case Else
                    StrCategory = "Miscellaneous"
            End Select
    
            MsgBox("=-= Department Store =-=" & vbCrLf & _
                   "---  Store Inventory ---" & vbCrLf & _
                   "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _
                   "Category:" & vbTab & StrCategory & vbCrLf & _
                   "Item Name:" & vbTab & ItemName & vbCrLf & _
                   "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _
                   "Department Store")
        End Sub
    End Class
  2. Access the DepartmentStore.vb file
  3. To use a StoreItem object, change the file as follows:
     
    Public Module DepartmentStore
    
        Public Function Main() As Integer
            Dim Nbr As Long
            Dim Classification As ItemCategory
            Dim Description As String
            Dim Value As Double
            Dim Item As StoreItem
    
            Nbr = 608432
            Classification = ItemCategory.Jewelry
            Description = "Silver 1/10-ct. T.W. Diamond Heart-Link Bracelet"
            Value = 95.85
    
            Item = New StoreItem
            Item.Initialize(Nbr, Classification, Description, Value)
            Item.ShowItem()
    
            Return 0
        End Function
    
    End Module
  4. Execute the application to see the result
     
    Department Store
  5. Close the form and return to your programming environment

Class Construction

 

The Default Constructor

When you declare a variable of a class, a special method must be called to initialize the members of that class. This method is automatically provided for every class and it is called a constructor. Whenever you create a new class, a constructor is automatically provided to it. This  particular constructor is called the default constructor. You have the option of creating it or not. Although a constructor is created for your class, you can customize its behavior or change it as you see fit.

The constructor of a class is called New and it is created as a sub procedure. Here is an example:

Public Class Square
        Public Sub New()
            
        End Sub
End Class

Like every method, a constructor is equipped with a body. In this body, you can access any of the member variables (or method(s)) of the same class. Consider the following program:

Public Module Exercise
    Private Class Square
        Public Sub New()
            MsgBox("Square Builder")
        End Sub
    End Class

    Public Function Main() As Integer
        Dim sq As Square = New Square

        Return 0
    End Function
End Module

When executed, it would produce:

Class

This shows that, when a class has been instantiated, its constructor is the first method to be called. For this reason, you can use a constructor to initialize a class, that is, to assign default values to its member variables. Based on this, instead of initializing the member variable(s) of a class when initializing it or them, or instead of creating a special method used to initialize the member variable(s) of a class, you can use a constructor to do this. The advantage of a constructor is that it doesn't need to be called: it is automatically available whenever the class is instantiated.

Practical LearningPractical Learning: Constructing a Class

  1. Create a Console Application named DepartmentStore4
  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. To create a new class, in the Solution Explorer, right-click DepartmentStore4 -> Add -> Class...
  5. Set the Name to StoreItem and click Add
  6. Change the file as follows:
     
    Public Enum ItemCategory
        Women
        Men
        Girls
        Boys
        Babies
        Jewelry
        Beauty
        Bedroom
        Miscellaneous
    End Enum
    
    Public Class StoreItem
        Friend ItemNumber As Long
        Friend Category As ItemCategory
        Friend ItemName As String
        Friend UnitPrice As Double
    
        Public Sub New()
            Me.ItemNumber = 0
            Me.Category = ItemCategory.Miscellaneous
            Me.ItemName = "Unknown"
            Me.UnitPrice = 0D
        End Sub
    
        Public Sub ShowItem()
            Dim StrCategory As String
    
            Select Case Category
                Case ItemCategory.Women
                    StrCategory = "Women"
                Case ItemCategory.Men
                    StrCategory = "Men"
                Case ItemCategory.Girls
                    StrCategory = "Girls"
                Case ItemCategory.Boys
                    StrCategory = "Boys"
                Case ItemCategory.Babies
                    StrCategory = "Babies"
                Case ItemCategory.Jewelry
                    StrCategory = "Jewelry"
                Case ItemCategory.Beauty
                    StrCategory = "Beauty"
                Case ItemCategory.Bedroom
                    StrCategory = "Bedroom"
                Case Else
                    StrCategory = "Miscellaneous"
            End Select
    
            MsgBox("=-= Department Store =-=" & vbCrLf & _
                   "---  Store Inventory ---" & vbCrLf & _
                   "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _
                   "Category:" & vbTab & StrCategory & vbCrLf & _
                   "Item Name:" & vbTab & ItemName & vbCrLf & _
                   "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _
                   "Department Store")
        End Sub
    End Class
  7. Access the DepartmentStore.vb file
  8. To use a StoreItem object, change the file as follows:
     
    Public Module DepartmentStore
    
        Public Function Main() As Integer
            Dim Item As StoreItem
    
            Item = New StoreItem
            Item.ShowItem()
    
            Return 0
        End Function
    
    End Module
  9. Execute the application to see the result
     
    Department Store
  10. Close the form and return to your programming environment

A Constructor With Argument(s)

In the previous section, we saw that there was always a default constructor for a new class that you create; you just havce the option of explicitly creating one or not. The default constructor as we saw it doesn't take arguments: this is not a rule, it is simply assumed. Instead of a default constructor, you may want to create a constructor that takes an argument. Here is an example:

Private Class Square
    Public Sub New(ByVal sd As Double)

    End Sub
End Class

With this type of constructor, when you declare an instance of the class, you can use this new constructor to initialize the class. Here is an example:

Public Module Exercise
    Private Class Square
        Public Sub New(ByVal sd As Double)
            MsgBox("Square Builder")
        End Sub
    End Class

    Public Function Main() As Integer
        Dim sqr As Square = New Square(38.64)

        Return 0
    End Function
End Module

If you create one constructor for your class and pass at least one argument to that constructor, the automatic default constructor created by the compiler disappears. This implies that if you declare an instance of the class and use the default constructor to initialize it, you would receive an error when you compile the program. Based on this, the following program will produce an error:

Public Module Exercise
    Private Class Square
        Public Sub New(ByVal sd As Double)
            MsgBox("Square Builder")
        End Sub
    End Class

    Public Function Main() As Integer
        Dim sqr As Square = New Square ' The default constructor is not available

        Return 0
    End Function
End Module

If you still want to use the default constructor in a class after creating a constructor that takes at least one argument, you must explicitly create that default constructor.

Practical Learning Practical Learning: Constructing a Class

  1. To pass arguments to a constructor, change the file as follows:
     
    Public Enum ItemCategory
        Women
        Men
        Girls
        Boys
        Babies
        Jewelry
        Beauty
        Bedroom
        Miscellaneous
    End Enum
    
    Public Class StoreItem
        Friend ItemNumber As Long
        Friend Category As ItemCategory
        Friend ItemName As String
        Friend UnitPrice As Double
    
        Public Sub New(ByVal Number As Long, _
                              ByVal Type As ItemCategory, _
                              ByVal Name As String, _
                              ByVal Price As Double)
            ItemNumber = Number
            Category = Type
            ItemName = Name
            UnitPrice = Price
        End Sub
    
        Public Sub ShowItem()
            Dim StrCategory As String
    
            Select Case Category
                Case ItemCategory.Women
                    StrCategory = "Women"
                Case ItemCategory.Men
                    StrCategory = "Men"
                Case ItemCategory.Girls
                    StrCategory = "Girls"
                Case ItemCategory.Boys
                    StrCategory = "Boys"
                Case ItemCategory.Babies
                    StrCategory = "Babies"
                Case ItemCategory.Jewelry
                    StrCategory = "Jewelry"
                Case ItemCategory.Beauty
                    StrCategory = "Beauty"
                Case ItemCategory.Bedroom
                    StrCategory = "Bedroom"
                Case Else
                    StrCategory = "Miscellaneous"
            End Select
    
            MsgBox("=-= Department Store =-=" & vbCrLf & _
                   "---  Store Inventory ---" & vbCrLf & _
                   "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _
                   "Category:" & vbTab & StrCategory & vbCrLf & _
                   "Item Name:" & vbTab & ItemName & vbCrLf & _
                   "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _
                   "Department Store")
        End Sub
    End Class
  2. Access the DepartmentStore.vb file and change it as follows:
     
    Public Module DepartmentStore
    
        Public Function Main() As Integer
            Dim Nbr As Long
            Dim Classification As ItemCategory
            Dim Description As String
            Dim Value As Double
            Dim Item As StoreItem
    
            Nbr = 759470
            Classification = ItemCategory.Men
            Description = "Multistriped Organic Cotton Dress Shirt"
            Value = 35.5
    
            Item = New StoreItem(Nbr, Classification, Description, Value)
            Item.ShowItem()
    
            Return 0
        End Function
    
    End Module
  3. Execute the application to see the result
     
    Department Store
  4. Close the form and return to your programming environment

Constructor Overloading

A constructor is the primary method of a class. It allows the programmer to initialize a variable of a class when the class is instantiated. A constructor that plays this role of initializing an instance of a class is also called an instance constructor. Most of the time, you don't need to create a constructor, since one is automatically provided to any class you create. Sometimes though, as we have seen in some classes, you need to create your own constructor as you judge it necessary and sometimes, a single constructor may not be sufficient. For example, when creating a class, you may decide, or find out, that there must be more than one way for a user to initialize a variable.

Like any other method, a constructor can be overloaded. In other words, you can create a class and give it more than one constructor. The same rules used on overloading regular methods also apply to constructors: the different constructors must have different number of arguments or different types of arguments.

Practical Learning Practical Learning: Overloading a Constructor

  1. Access the StoreItem.vb file
  2. To overload the constructor, change the file as follows:
     
    Public Enum ItemCategory
        Women
        Men
        Girls
        Boys
        Babies
        Jewelry
        Beauty
        Bedroom
        Miscellaneous
    End Enum
    
    Public Class StoreItem
        Friend ItemNumber As Long
        Friend Category As ItemCategory
        Friend ItemName As String
        Friend ItemSize As String
        Friend UnitPrice As Double
    
        REM Default Constructor, used to initialize an unidentified object
        Public Sub New()
            Me.ItemNumber = 0
            Me.Category = ItemCategory.Miscellaneous
            Me.ItemName = "Unknown"
            Me.ItemSize = "Unknown or Fits All"
            Me.UnitPrice = 0D
        End Sub
    
        REM This constructor is for items without size (jewelry, beauty, etc)
        Public Sub New(ByVal Number As Long, _
                       ByVal Type As ItemCategory, _
                       ByVal Name As String, _
                       ByVal Price As Double)
            Me.ItemNumber = Number
            Me.Category = Type
            Me.ItemName = Name
            Me.UnitPrice = Price
        End Sub
    
        REM This constructor is used to identify an item to wear
        Public Sub New(ByVal Number As Long, _
                       ByVal Type As ItemCategory, _
                       ByVal Name As String, _
                       ByVal Size As String, _
                       ByVal Price As Double)
            Me.ItemNumber = Number
            Me.Category = Type
            Me.ItemName = Name
            Me.ItemSize = Size
            Me.UnitPrice = Price
        End Sub
    
        REM This method is used to display a description of an item
        REM The caller will determine whether the item has a size or not
        Public Sub ShowItem(ByVal HasSize As Boolean)
            Dim StrCategory As String
    
            Select Case Category
                Case ItemCategory.Women
                    StrCategory = "Women"
                Case ItemCategory.Men
                    StrCategory = "Men"
                Case ItemCategory.Girls
                    StrCategory = "Girls"
                Case ItemCategory.Boys
                    StrCategory = "Boys"
                Case ItemCategory.Babies
                    StrCategory = "Babies"
                Case ItemCategory.Jewelry
                    StrCategory = "Jewelry"
                Case ItemCategory.Beauty
                    StrCategory = "Beauty"
                Case ItemCategory.Bedroom
                    StrCategory = "Bedroom"
                Case Else
                    StrCategory = "Miscellaneous"
            End Select
    
            If HasSize = True Then
                MsgBox("=-= Department Store =-=" & vbCrLf & _
                       "---  Store Inventory ---" & vbCrLf & _
                       "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _
                       "Category:" & vbTab & StrCategory & vbCrLf & _
                       "Item Name:" & vbTab & ItemName & vbCrLf & _
                       "Size:" & vbTab & vbTab & ItemSize & vbCrLf & _
                       "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _
                       MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _
                       "Department Store")
            Else
                MsgBox("=-= Department Store =-=" & vbCrLf & _
                       "---  Store Inventory ---" & vbCrLf & _
                       "Item #:" & vbTab & vbTab & ItemNumber & vbCrLf & _
                       "Category:" & vbTab & StrCategory & vbCrLf & _
                       "Item Name:" & vbTab & ItemName & vbCrLf & _
                       "Unit Price:" & vbTab & FormatCurrency(UnitPrice), _
                       MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, _
                       "Department Store")
            End If
        End Sub
    End Class
  3. Access the DepartmentStore.vb file and change it as follow:
     
    Public Module DepartmentStore
    
        Public Function Main() As Integer
            Dim Nbr As Long
            Dim Classification As ItemCategory
            Dim Description As String
            Dim Size As String
            Dim Value As Double
            Dim Item As StoreItem
    
            REM Using the default constructor
            Item = New StoreItem
            Item.ShowItem(True)
    
            Nbr = 608432
            Classification = ItemCategory.Jewelry
            Description = "Silver 1/10-ct. T.W. Diamond Heart-Link Bracelet"
            Value = 95.85
    
            REM Using the constructor that takes 4 arguments
            Item = New StoreItem(Nbr, Classification, Description, Value)
            Item.ShowItem(False)
    
            Nbr = 437876
            Classification = ItemCategory.Women
            Description = "Crinkled Georgette Dress"
            Size = "Medium"
            Value = 42.95
    
            REM Using the constructor that takes 5 arguments
            REM after initialing a Women object
            Item = New StoreItem(Nbr, ItemCategory.Women, _
                                 Description, Size, Value)
            Item.ShowItem(True)
    
            REM Using the constructor that takes 5 arguments
            REM Directly initialing the constructor
            Item = New StoreItem(790475, ItemCategory.Men, _
                                 "New Wool Comfort Pants", "36x33", 38.75)
            Item.ShowItem(True)
    
            REM Using the constructor that takes 5 arguments
            REM Initialing the values in random order
            Item = New StoreItem(Type:=ItemCategory.Women, _
                                 Size:="9 1/2 W", _
                                 Price:=35.5, _
                                 Name:="Modest Dress Heels", _
                                 Number:=487046)
            Item.ShowItem(True)
    
            Return 0
        End Function
    
    End Module
  4. Execute the application to see the result:
     
    Department Store
    Department Store
    Department Store
    Department Store Department Store
  5. Close the form and return to your programming environment
   
 

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