Home

The Methods of a Class

Introduction to the Methods of a Class

Overview

A procedure or a function can be created in the body, as a member, of a class to perform actions for, or on behalf of, the class. Such a procedure or member function is called a method.

To create a method, in the body of a class, use the same formulas as for procedures and functions. Here is an example of a function method:

<script Language="VB" runat="server">
Public Class Depreciation

    Function Calculate()

    End Function

End Class
</script>

When you have created a member variable in a class, it is available to all methods of the same class. This means that, to use it from a method of the same class, you don't have to declare a variable for the class. Here is an example:

<script Language="VB" runat="server">
Public Class Depreciation
    Public Cost As Double
    Public SalvageValue As Double
    Public EstimatedLife As Integer

    Function Calculate()
        Return (Cost - SalvageValue) / EstimatedLife
    End Function
End Class
</script>

A Public Method

A method is said to be hidden if it cannot be accessed outside the class but can be accessed only by other members of the same class, in the body of the class. A method is referred to as public if it can be accessed by objects outside the class. To specify that a method is public, precede it with the Public keyword. Here is an example:

<script Language="VB" runat="server">
Public Class Depreciation
    Public Cost As Double
    Public SalvageValue As Double
    Public EstimatedLife As Integer

    Public Function Calculate()
        Return (Cost - SalvageValue) / EstimatedLife
    End Function
End Class
</script>

Accessing a Method Outside the Class

To access a method outside of its class, use the same period operator for member variables. Here is an example

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head>
<script Language="VB" runat="server">
Public Class Depreciation
    Public Cost As Double
    Public SalvageValue As Double
    Public EstimatedLife As Integer

    Public Function Calculate()
        Return (Cost - SalvageValue) / EstimatedLife
    End Function
End Class
</script>

<title>Depreciation - Straight-Line Method</title>
</head>
<body>
<h4>Depreciation - Straight-Line Method</h4>

<%
Dim d As Double
Dim Vehicle As Depreciation

Vehicle = New Depreciation

Vehicle.Cost = 45800
Vehicle.SalvageValue = 6000
Vehicle.EstimatedLife = 6

d = Vehicle.Calculate()

Response.Write("Machine Cost: " & Vehicle.Cost)
Response.Write("<br>Salvage Value: " & Vehicle.SalvageValue)
Response.Write("<br>Estimated Life: " & Vehicle.EstimatedLife & " Years")
Response.Write("<br>Depreciation: " & d & "/Year")
%>

</body>
</html>

This would produce:

Accessing a Method Outside the Class

In the same way, you can use a With statement to access a method of a class. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head>
<script runat="server">
Public Class Depreciation
    Public Cost As Double
    Public SalvageValue As Double
    Public EstimatedLife As Integer

    Public Function CalculateDepression()
        Return (Cost - SalvageValue) / EstimatedLife
    End Function
End Class
</script>

<title>Depreciation - Straight-Line Method</title>
</head>
<body>
<h4>Depreciation - Straight-Line Method</h4>

<%
Dim printer As New Depreciation
Dim evaluation As Double

With printer
    .Cost = 725
    .SalvageValue = 200
    .EstimatedLife = 2
    evaluation = .CalculateDepression()

    Response.Write("Machine Cost: " & .Cost)
    Response.Write("<br>Salvage Value: " & .SalvageValue)
    Response.Write("<br>Estimated Life: " & .EstimatedLife & " Years")
    Response.Write("<br>Depreciation: " & Evaluation & "/Year")
End With
%>

</body>
</html>

This would produce:

Accessing a Method Outside the Class

Methods and Arguments

Introduction

Like regular procedures, a method can have one or more parameters. The rules are the same as those applied to regular procedures or functions. Because a method has direct access to all regular members of its class, you don't have to create a parameter for a member variable of the same class. You would need a parameter only if an external value would be passed to the method. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head>

<script runat="server">
Public Class Employee
    Public EmployeeNumber As Integer
    Public FirstName As String
    Public LastName As String
    Public HourlySalary As Double

    Public Function CalculateNetPay(ByVal time As Double) As Double
        Return HourlySalary * time
    End Function
End Class
</script>

<title>Department Store - Payroll Evaluation</title>
</head>
<body>
<h3>Department Store</h3>
<p><b>Payroll Evaluation</b></p>
<%
Dim hSalary As Double
Dim timeWorked As Double
Dim netPay As Double
Dim staff As New Employee

staff.EmployeeNumber = 630485
staff.FirstName = "David"
staff.LastName = "Salomons"
staff.HourlySalary = 18.95

timeWorked = 44.50

netPay = staff.CalculateNetPay(timeWorked)

Response.Write("<table><tr><td>Employee #:</td><td>")
Response.Write(staff.EmployeeNumber)
Response.Write("</td></tr><tr><td>First Name:</td><td>")
Response.Write(staff.FirstName)
Response.Write("</td></tr><tr><td>Last Name :</td><td>")
Response.Write(staff.LastName)
Response.Write("</td></tr><tr><td>Hourly Salary:</td><td>")
Response.Write(staff.HourlySalary)
Response.Write("</td></tr><tr><td>Time Worked:</td><td>")
Response.Write(timeWorked)
Response.Write("</td></tr><tr><td>Net Pay:</td><td>")
Response.Write(netPay)
Response.Write("</td></tr></table>")
%>

</body>
</html>

This would produce:

Constants

Method 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 parameters:

  • They can have different types of parameters
  • They can have a different number of parameters

Any or both of these two rules must be respected. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head>

<script runat="server">
Public Class Employee
    Public EmployeeNumber As Integer
    Public FirstName As String
    Public LastName As String
    Public HourlySalary As Double

    Public Function CalculateNetPay(ByVal time As Double) As Double
        Return HourlySalary * time
    End Function

    Public Function CalculateNetPay(ByVal time As Double,
    				    ByVal period As String) As String
        Return (HourlySalary * time) & "/" & period
    End Function
End Class
</script>

<title>Department Store - Payroll Evaluation</title>
</head>
<body>
<h3>Department Store</h3>
<p><b>Payroll Evaluation</b></p>
<%
Dim hSalary As Double
Dim timeWorked As Double
Dim netPay As String
Dim staff As New Employee

staff.EmployeeNumber = 630485
staff.FirstName = "David"
staff.LastName = "Salomons"
staff.HourlySalary = 18.95

timeWorked = 44.50

netPay = staff.CalculateNetPay(timeWorked, "Week")

Response.Write("<table><tr><td>Employee #:</td><td>")
Response.Write(staff.EmployeeNumber)
Response.Write("</td></tr><tr><td>First Name:</td><td>")
Response.Write(staff.FirstName)
Response.Write("</td></tr><tr><td>Last Name :</td><td>")
Response.Write(staff.LastName)
Response.Write("</td></tr><tr><td>Hourly Salary:</td><td>")
Response.Write(staff.HourlySalary)
Response.Write("</td></tr><tr><td>Time Worked:</td><td>")
Response.Write(timeWorked)
Response.Write("</td></tr><tr><td>Net Pay:</td><td>")
Response.Write(netPay)
Response.Write("</td></tr></table>")
%>

</body>
</html>

This would produce:

Method Overloading

As mentioned for the regular procedures, remember that, to further indicate that the methods are overloaded, type the Overloads keyword to their left. Here are examples:

<script runat="server">
Public Class Employee
    Public EmployeeNumber As Integer
    Public FirstName As String
    Public LastName As String
    Public HourlySalary As Double

    Public Overloads Function CalculateNetPay(ByVal time As Double) As Double
        Return HourlySalary * time
    End Function

    Public Overloads Function CalculateNetPay(ByVal time As Double,
    				    ByVal period As String) As String
        Return (HourlySalary * time) & "/" & period
    End Function
End Class
</script>

Optional Arguments

As seen for regular procedures and functions, a method can use one or more parameters that are optional. To specify that an argument is optional, when creating the method, type the Optional keyword to the left of the parameter and assign a default value to it. When calling the method, you can pass or ignore the argument. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head>
<script runat="server">
Class StoreItem
    Public ItemNumber As Integer
    Public ItemName As String
    Public Size As String
    Public UnitPrice As Double

    Public Function CalculateDiscountAmount(Optional ByVal DiscountRate As Double = 20.0) As Double
        Return UnitPrice * DiscountRate / 100.0
    End Function
End Class
</script>

<title>Department Store - Inventory</title>
</head>
<body>
<h4>Department Store</h4>
<p><b>Store Inventory</b></p>

<%
Dim item As New StoreItem
Dim discount As Double,
    markedPrice as double

item.ItemNumber = 927497
item.ItemName   = "Leaf Print Short Sleeve Shift Dress"
item.Size       =  "Medium"
item.UnitPrice  = 59.50

discount = item.CalculateDiscountAmount()
markedPrice = item.UnitPrice - discount

Response.Write("Item #: " & item.ItemNumber)
Response.Write("<br>Item Name: " & item.ItemName)
Response.Write("<br>Item Size: " & item.Size)
Response.Write("<br>Unit Price: " & item.UnitPrice)
Response.Write("<br>Discount Amount: " & discount)
Response.Write("<br>Marked Price: " & markedPrice & "<br>")

item.ItemNumber = 480795
item.ItemName   = "Small-Plaid Shirt"
item.Size       =  "Large"
item.UnitPrice  = 34.95

discount = item.CalculateDiscountAmount(35)
markedPrice = item.UnitPrice - discount

Response.Write("<br>Item #: " & item.ItemNumber)
Response.Write("<br>Item Name: " & item.ItemName)
Response.Write("<br>Item Size: " & item.Size)
Response.Write("<br>Unit Price: " & item.UnitPrice)
Response.Write("<br>Discount Amount: " & discount)
Response.Write("<br>Marked Price: " & markedPrice & "<br>")
%>

</body>
</html>

The rules of optional arguments in methods are the same rules reviewed for regular procedures and functions.

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. You can then access the member variables of the class using that variable followed by a period and the desired member. As an alternative, you can use the name of the class and directly access a member variable without primarily declaring a variable of the class. In order to access a member variable like that, you must explicitly create it as shared.

To create a shared member variable, type the Shared keyword on its left when creating it in the body of the class. After the shared member variable has been created, 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:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class Rectangle
    Public Length As Double
    Public Shared Height As Double
End Class
</script>
<title>Geometry</title>
</head>
<body>
<%
REM Notice that a Rectangle variable is not declared
Rectangle.Height = 20.68

Response.Write("Rectangle Characteristics<br>" &
               "Height:" & Rectangle.Height)
%>
</body>
</html>

This would produce:

A Shared Member Variable

Notice that a variable was not declared in order to access the 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.

Shared Methods

Like member variables, a method can be shared among classes. 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:

<script runat="server">
Friend Class Rectangle
    Shared Function CalculatePerimeter#()
        Return (Length + Height) * 2
    End Function
End Class
</script>

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

<script runat="server">
Friend Class Rectangle
    Public Shared Function CalculatePerimeter#()

    End Function

    Public Shared Function CalcaulteArea#()

    End Function
End Class
</script>

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:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public 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
</script>
<title>Geometry</title>
</head>
<body>
<%
REM Notice that a Rectangle variable is not declared
Rectangle.Height = 20.68
Rectangle.Length = 32.47

Response.Write("Rectangle Characteristics" &
               "<br>Length: " & Rectangle.Length &
               "<br>Height: " & Rectangle.Height &
               "<br>Perimeter: " & Rectangle.CalculatePerimeter#() &
               "<br>Area: " & Rectangle.CalcaulteArea#())
%>
</body>
</html>

This would produce:

Shared Methods

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:

<script runat="server">
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
</script>

You can use a special object that allows you to access the member(s) of a class while inside the class. This object 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:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class Triangle
    Public Base As Double
    Public Height As Double

    Public Function CalculateArea()
        Dim Area As Double

        ' Using "Me" to access the members of this class
        Me.Base = 24.55
        Me.Height = 20.75

        ' You cannot use Me to access Area because Area 
        ' is not a member of this class
        Area = Me.Base * Me.Height / 2

        CalculateArea = Area
    End Function
End Class
</script>
<title>Geometry</title>
</head>
<body>
<%
Dim tri As Triangle = New Triangle

Response.Write("Triangle Characteristics" &
                       "<br>Area: " & tri.CalculateArea())
%>
</body>
</html>

This would produce:

Me

Because Me is an object, you can assign it to a variable that refers to an object of the same class. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class Triangle
    Public Sub Examine()
        Dim inside = Me
    End Sub
End Class
</script>
<title>Geometry</title>
</head>
<body>
</body>
</html>

You can also compare an object to Me to find out what that object represents.

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
 
 
 

Class Construction

Introduction

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.

The Default Constructor

Whenever you create a new class, a constructor is automatically created for 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:

<script runat="server">
Public Class Square
    Public Sub New()
            
    End Sub
End Class
</script>

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:

<script runat="server">
Public Class Square
    Public Side As Double

    Public Sub New()
        Side = 0.00
    End Sub
End Class
</script>

Like we have done so far, to create an object, you can declare a variable of the class. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class Square
    Public Side As Double

    Public Sub New()
        Side = 27.93
    End Sub
End Class
</script>
<title>Geometry</title>
</head>
<body>
<%
Dim sq As Square

sq = New Square

Response.Write("Square Characteristics")
Response.Write("<br>Square: " & sq.Side)
%>
</body>
</html>

This would produce:

The Default Constructor

Notice that the member variable was initialized in the constructor and not where the object was created. Also notice that the value given to the member in the constructor is the same that displays on the webpage. This shows that, when a class is 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 an object is created.

So far, when creating an object, we only used the name of the class. To indicate that you are using the default constructor of the class when creating an object, you can add parentheses to the name of the class after the New operator. Here are examples:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head>
<script runat="server">
Public Class Depreciation
    Public Cost As Double
    Public SalvageValue As Double
    Public EstimatedLife As Integer
End Class
</script>

<title>Depreciation - Straight-Line Method</title>
</head>
<body>
<h4>Depreciation - Straight-Line Method</h4>

<%
Dim vehicle As Depreciation

vehicle = New Depreciation()

Dim printer = New Depreciation()
%>

</body>
</html>

Any of these techniques produces the same result.

A Constructor With a Parameter

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

<script runat="server">
Public Class Square
    Public Sub New(ByVal sd As Double)

    End Sub
End Class
</script>

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

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class Square
    Public Sub New(ByVal sd As Double)

    End Sub
End Class
</script>
<title>Geometry</title>
</head>
<body>
<%

Dim sqr As Square = New Square(38.64)

%>
</body>
</html>

One of the roles of a construtor with a parameter is to allow code outside the object to pass a value to a member variable of the class. To make this possible, you can initialize the member variable with the parameter of the constructor. Here is an example:

<script runat="server">
Public Class Square
    Public Side As Double

    Public Sub New(ByVal sd As Double)
	Side = sd
    End Sub
End Class
</script>

Remember that other methods of the class have direct access to the member variables of the same class. Here are two examples:

<script runat="server">
Public Class Square
    Public Side As Double

    Public Sub New(ByVal sd As Double)
	Side = sd
    End Sub

    Public Function CalculatePerimeter()
        CalculatePerimeter = Side * 4.00
    End Function

    Public Function CalculateArea()
        Return Side * Side
    End Function
End Class
</script>

Also remember that, inside the class, you can use the Me object to access the non-shared member variables of the same class. Here are examples:

<script runat="server">
Public Class Square
    Public Side As Double

    Public Sub New(ByVal sd As Double)
	Me.Side = sd
    End Sub

    Public Function CalculatePerimeter()
        CalculatePerimeter = Me.Side * 4.00
    End Function

    Public Function CalculateArea()
        Return Me.Side * Me.Side
    End Function
End Class
</script>

If you create a constructor that uses a parameter, when declaring a variable for the class, that is, when creating an object, you must pass a value to the constructor. As mentioned in the previous sections, that value would be assigned to the member variable. When the member variable is accessed outside the class, the member would be holding the value that was passed. Consider the following code:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class Square
    Public Side As Double

    Public Sub New(ByVal sd As Double)
        Side = sd
    End Sub

    Public Function CalculatePerimeter()
        CalculatePerimeter = Side * 4.0
    End Function

    Public Function CalculateArea()
        Return Side * Side
    End Function
End Class

</script>
<style type="text/css">
#main-title
{
    font-size: 1.28em;
    font-weight: bold;
    text-align: center;
    font-family: Georgia, Garamond, Times New Roman, Times, serif;
}
#whole
{
    margin: auto;
    width:  215px;
}
#tblSquare { width: 210px; }
</style>
<title>Geometry - Square</title>
</head>
<body>
<form id="frmSquare" runat="server">
<div id="whole">

<%
Dim sqr As Square = New Square(38.64)

Response.Write("<p id='main-title'>Geometry - Square</p>")

Response.Write("<table id='tblSquare' border=4>")
Response.Write("<tr><td><b>Side:</b></td><td>" & sqr.Side & "</td></tr>")
Response.Write("<tr><td><b>Perimeter:</b></td><td>" &
		sqr.CalculatePerimeter() & "</td></tr>")
Response.Write("<tr><td><b>Area:</b></td><td>" & sqr.CalculateArea() & "</td></tr>")
Response.Write("</table>")
%>
</div>
</form>
</body>
</html>

This would produce:

The Default Constructor

Constructor Overloading

A class can have more than one constructor, which is referred to as overloading. The same rules used on overloading regular methods also apply to constructors: the different constructors can have different numbers of parameters. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class Quadrilateral
        Public Width As Double
        Public Height As Double

        REM If the shape is a square, both sides are the same
        Public Sub New(ByVal w As Double)
            Me.Width = w
            Me.Height = w
        End Sub

        REM If the shape is a rectangle, the sides are different
        Public Sub New(ByVal w As Double, ByVal h As Double)
            Me.Width = w
            Me.Height = h
        End Sub

        Public Function CalculateArea()
            Return Me.Width * Me.Height
        End Function
    End Class

</script>
<style type="text/css">
#main-title
{
    font-size: 1.08em;
    font-weight: bold;
    text-align: center;
    font-family: Georgia, Garamond, Times New Roman, Times, serif;
}
#whole
{
    margin: auto;
    width:  215px;
}
.tblShape { width: 210px; }
</style>
<title>Geometry - Quadrilateral</title>
</head>
<body>
<form id="frmSquare" runat="server">
<div id="whole">

<%
    ' A square
    Dim sqr As New Quadrilateral(38.64)
    ' A rectangle
    Dim rect As New Quadrilateral(38.64, 25.73)

    Response.Write("<p id='main-title'>Geometry - Square</p>")

    Response.Write("<table class='tblShape' border=4>")
    Response.Write("<tr><td><b>Side:</b></td><td>" & sqr.Width & "</td></tr>")
    Response.Write("<tr><td><b>Area:</b></td><td>" & sqr.CalculateArea() & "</td></tr>")
    Response.Write("</table>")

    Response.Write("<p id='main-title'>Geometry - Rectangle</p>")

    Response.Write("<table class='tblShape' border=4>")
    Response.Write("<tr><td><b>Width:</b></td><td>" & rect.Width & "</td></tr>")
    Response.Write("<tr><td><b>Height:</b></td><td>" & rect.Height & "</td></tr>")
    Response.Write("<tr><td><b>Area:</b></td><td>" & rect.CalculateArea() & "</td></tr>")
    Response.Write("</table>")
%>
</div>
</form>
</body>
</html>

This would produce:

Constructor Overloading

An alternative is for constructors to have different types of arguments.

If you create a constructor for your class and use a parameter in its parentheses, the automatic default constructor 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. If you want to use the default constructor in a class after creating a constructor that takes at least one parameter, you must explicitly create that default constructor. Here is an example:

<script runat="server">
Public Class Quadrilateral
    Public Width As Double
    Public Height As Double

    Public Sub New()
        Me.Width = 0.00
        Me.Height = 0.00
    End Sub

    REM If the shape is a square, both sides are the same
    Public Sub New(ByVal w As Double)
        Me.Width = w
        Me.Height = w
    End Sub

    REM If the shape is a rectangle, the sides are different
    Public Sub New(ByVal w As Double, ByVal h As Double)
        Me.Width = w
        Me.Height = h
    End Sub

    Public Function CalculateArea()
        Return Me.Width * Me.Height
    End Function
End Class
</script>

A Constructor With Many Parameters

Remember that, if you create a constructor that uses many parameters and you want to create an object using that constructor, you must specify a value for each parameter and in the order they appear in the constructor. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head>

<script runat="server">
Public Class Student
    Public StudentNumber As String
    Public FirstName     As String
    Public LastName      As String
    Public Gender        As Char

    Public Sub New(ByVal nbr As String, ByVal first As String, ByVal last As String, ByVal gdr As Char)
        Me.StudentNumber = nbr 
        Me.FirstName     = first
        Me.LastName      = last 
        Me.Gender        = gdr   
    End Sub
End Class
</script>

<title>Student Registration</title>
</head>
<body>

<%
    Dim pupil As New Student("92-1708-24", "Paul", "Hands", "M")

    Response.Write("<h3>Student Registration</h3>")
    Response.Write("<table border=2><tr><td>Student #:</td><td>")
    Response.Write(pupil.StudentNumber)
    Response.Write("</td></tr><tr><td>First Name:</td><td>")
    Response.Write(pupil.FirstName)
    Response.Write("</td></tr><tr><td>Last Name :</td><td>")
    Response.Write(pupil.LastName)
    Response.Write("</td></tr><tr><td>Gender:</td><td>")
    Response.Write(pupil.Gender)
    Response.Write("</td></tr></table>")
%>

</body>
</html>

This would produce:

A Constructor With Many Parameters

As seen for functions and methods, instead of passing the arguments in the exact order of the parameters, you can access the parameters by name and assign the desired value to each. Remember that the assignment is done using the := operator and separate the arguments by commas. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head>

<script runat="server">
Public Class Student
    Public StudentNumber As String
    Public FirstName     As String
    Public LastName      As String
    Public Gender        As Char

    Public Sub New(ByVal nbr As String, ByVal first As String, ByVal last As String, ByVal gdr As Char)
        Me.StudentNumber = nbr 
        Me.FirstName     = first
        Me.LastName      = last 
        Me.Gender        = gdr   
    End Sub
End Class
</script>

<title>Student Registration</title>
</head>
<body>

<%
    Dim pupil As New Student(gdr := "F", first := "Priscilla", nbr := "18-2938-74", last := "Robertson")

    Response.Write("<h2>=--= Student Registration =--=</h2>")
    Response.Write("<table border=2><tr><td>Student #:</td><td>")
    Response.Write(pupil.StudentNumber)
    Response.Write("</td></tr><tr><td>First Name:</td><td>")
    Response.Write(pupil.FirstName)
    Response.Write("</td></tr><tr><td>Last Name :</td><td>")
    Response.Write(pupil.LastName)
    Response.Write("</td></tr><tr><td>Gender:</td><td>")
    Response.Write(pupil.Gender)
    Response.Write("</td></tr></table>")
%>

</body>
</html>

Of course, to make your code easy to read, you can pass the arguments on separate lines. Here is an example:

<%

    Dim pupil As New Student(gdr   := "F",
			     first := "Priscilla",
			     nbr   := "18-2938-74",
			     last  := "Robertson")

%>

Classes Combinations

Class Nesting

A class can be created inside of another class. A class created inside of another is referred to as nested. To nest a class, simply create it as you would any other. Here is an example of a class called Inside that is nested in a class called Outside:

<script runat="server">
Public Class Outside
    Public Class Inside

    End Class
End Class
</script>

In the same way, you can nest as many classes as you wish in another class and you can nest as many classes inside of other nested classes if you judge it necessary.

When you create one class inside of another, there is no special programmatic relationship between both classes: just because a class is nested does not mean that the nested class has immediate access to the members of the nesting class. They are two different classes and they can be used separately.

The name of a nested class is not "visible" outside of the nesting class. To access a nested class outside of the nesting class, you must qualify the name of the nested class anywhere you want to use it. For example, if you want to declare a variable for an inside class but outside , you must qualify its name. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class Outside
    Public Class Inside
        Public Sub New()
              
        End Sub
    End Class

    Public Sub New()
            
     End Sub
End Class

</script>
<title>Exercise</title>
</head>
<body>

<%
Dim Out As Outside = New Outside

Dim Ins As Outside.Inside = New Outside.Inside
%>
</body>
</html>;

Because there is no programmatically privileged relationship between a nested class and the nesting class, if you want to access the nested class in the nesting class, you can use its shared members. In the same way, if you want to access the nesting class in the nested class, you can go through the shared members of the nesting class.

Instead of shared members, if you want to access members of a nested class in the nesting class, you can first declare a variable of the nested class in the nesting class. In the same way, if you want to access members of a nesting class in the nested class, you can first declare a variable of the nesting class in the nested class.

A Class as a Member Variable

Just like any of the variables we have used so far, you can use a class to create a member variable of another class. You can use your own class or use one of the classes already available. Here is an example:

<script runat="server">
Public Class Point
    Dim x As Short
    Dim y As Short
End Class

Public Class CoordinateSystem
    Dim start As Point
End Class
</script>

After a member variable has been created as a class type of another class, it can be used regularly. Because the member is a class, declared as a reference, there are some rules you must follow to use it. After declaring the member variable, you must make sure you have allocated memory for it. You must also make sure that the variable is initialized appropriately before it can be used.

Returning an Object From a Method

As done for a value of a regular type, you can return an object value from a method of a class. To do this, you can first declare the method and specify the class as the return type. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head>
<script runat="server">
Public Class RightTriangle
    Public Length As Double
    Public Height As Double

    Public Sub New(ByVal len As Double, ByVal hgt As Double)
        Length = len
        Height = hgt
    End Sub
End Class

Function Create() As RightTriangle
    Return New RightTriangle(48.12, 29.73)
End Function
</script>

<title>Geometry: Right-Triangle</title>
</head>
<body>
<h5>Geometry: Right-Triangle</h5>

<%
    Dim tri As RightTriangle

    tri = Create()

    Response.Write("Length: " & tri.Length)
    Response.Write("<br>Height: " & tri.Height)
%>

</body>
</html>

This would produce:

A Constructor With Many Parameters

After implementing the method, you must return a value that is conform to the class. Once a method has returned a value of a class, the value can be used as normally as possible.

Passing an Object as Argument

A class can be used as a parameter to a procedure or to a method of another class. When a class is passed as argument:

  • Its public members are available to procedures and classes of its project, and procedures and classes of other projects
  • Its friendly members are available to the procedures and classes of the same project

As done for the arguments of primitive types, in the body of the procedure gets the argument, access its public or friendly members and use them as you see fit.

As done for the parameters of primitive types, you can pass more than one class as parameter to a method. Because classes are always used as references, when using a class as parameter, it is implied to be passed by reference. To reinforce this, you can type the ByRef keyword to the left of the argument.

Involving a Class and its Own Methods

Passing a Class as its Own Argument

An instance of a class can be passed as an argument to one of its own methods. To do this, you primarily pass the argument as if it were any class. Here is an example:

<script runat="server">
Public Class Point
    Dim x As Integer
    Dim y As Integer

    Public Sub Equivalent(ByVal Same As Point)

    End Sub
End Class
</script>

Then, in the body of the method, do whatever you want. You can, or you may not, use the parameter. Still, if you decide to use the argument, know that all of the other members of the class are available through the argument. Probably the simplest way to use the argument is the assign each of its values to the equivalent member of the class. Here is an example:

<script runat="server">
Public Class Point
    Dim x As Integer
    Dim y As Integer

    Public Sub Equivalent(ByVal Same As Point)
        Me.x = Same.x
        Me.y = Same.y
    End Sub
End Class
</script>

When calling the method, make sure you pass an instance of the class to it. You can first create and define the class, then pass it.

As mentioned previously, you can also compare an argument to Me to find out what class that argument is referring to. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class Triangle
    Dim edge As Double

    Public Sub Examine(ByVal face3 As Triangle)
        If face3 Is Me Then
            edge = 1.0
        End If
    End Sub
End Class
</script>
<title>Geometry</title>
</head>
<body>
</body>
</html>

Returning a Class From its Own Method

You can create a method in a class and make the method return an instance of the class. To start, on the left side of the method, enter the name of the class. Here is an example:

<script runat="server">
Public Class Point
    Public Function method-name() As Point

    End Function
End Class
</script>

There are various ways you can deal with the method. If you want to return a new value of the class, you can declare an instance of the class, initialize it, and then return it. Here is an example:

<script runat="server">
Public Class Point
    Dim x As Integer
    Dim y As Integer

    Public Sub New()

    End Sub

    Public Sub New(ByVal XCoord As Integer, ByVal YCoord As Integer)
        Me.x = XCoord
        Me.y = YCoord
    End Sub

    Public Sub New(ByVal Same As Point)
        Me.x = Same.x
        Me.x = Same.x
    End Sub

    Public Function AdvanceBy5() As Point
        Dim some As Point = New Point
        some.x = 5
        some.y = 5

        Return some
    End Function
End Class
</script>

Characteristics of Members of a Class

Constant Member Variables

You can make a member variable of class to be constant. To do this, type the Const keyword on the left side of the name of the variable and initialize it. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
Public Class Circle
    Const PI = 3.14159265359

    Public Radius As Double

    Public Sub New(ByVal radius)
        Me.Radius = radius
    End Sub

    Public Function CalculateArea()
            CalculateArea = Me.Radius * Me.Radius * PI
    End Function
End Class
</script>
<title>Geometry: Circle</title>
</head>
<body>
<h3>Geometry: Circle</h3>

<%
Dim disc = New Circle(48.37)

Response.Write("Radius: ")
Response.Write(disc.Radius)
Response.Write("<br>Area: ")
Response.Write(disc.CalculateArea)
%>
</body>
</html>

This would produce:

Constant Member Variables

Read-Only Member Variables

A member variable of a class is referred to as read-only if its value cannot be changed by objects outside the class. Unlike a constant variable that you must initialize when creating it, you can create a read-only variable in the class without initializing it.

To create a read-only member variable, on the left side of the name of the member, type ReadOnly.  This would be done as follows:

Public ReadOnly PI As Double

After declaring the variable, you should initialize it. You can do this when declaring it, as done for a constant. Here is an example:

<script runat="server">
Public Class Circle
    Public ReadOnly PI = 3.14159265359

    Public Radius As Double

    Public Sub New(ByVal radius)
        Me.Radius = radius
    End Sub

    Public Function CalculateArea()
            CalculateArea = Me.Radius * Me.Radius * PI
    End Function
End Class
</script>

Alternatively, you can initialize the variable in the(a) constructor of its class. This would be done as follows:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
Public Class Circle
    Public ReadOnly PI

    Public Radius As Double

    Public Sub New(ByVal radius)
        PI = 3.14159265359

        Me.Radius = radius
    End Sub

    Public Function CalculateCircumference()
            CalculateCircumference = Me.Radius * 2.00 * PI
    End Function

    Public Function CalculateArea()
            CalculateArea = Me.Radius * Me.Radius * PI
    End Function
End Class
</script>
<title>Geometry: Circle</title>
</head>
<body>
<h3>Geometry: Circle</h3>

<%
Dim disc = New Circle(48.37)

Response.Write("Radius: ")
Response.Write(disc.Radius)
Response.Write("<br>Area: ")
Response.Write(disc.CalculateArea)
Response.Write("<br>Circumference: ")
Response.Write(disc.CalculateCircumference)
%>
</body>
</html>

This would produce:

Read-Only Member Variables

If the value held by a read-only member variable is gotten from an expression, then the value should be initialized in the(a) construction with the desired expression. If you don't rightly initialize it, the compiler would initialize it with the default value based on the type of that variable. Therefore, you should make sure you initialize your ReadOnly member variables in a constructor, if those variables are based on an expression. Here are a few examples:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
Public Class Circle
    Public Radius As Double
    Public Const Twice As Integer = 2.00
    Public ReadOnly PI As Double
    Public ReadOnly Diameter As Double
    Public ReadOnly Circumference As Double
    Public ReadOnly Area As Double

    Public Sub New(ByVal radius)
        PI = 3.14159265359
        Me.Radius = radius
        Diameter = Radius * Twice
        Circumference = Diameter * PI
        Area = Radius * Radius * PI
    End Sub
End Class
</script>
<title>Geometry: Circle</title>
</head>
<body>
<h3>Geometry: Circle</h3>

<%
Dim disc = New Circle(48.37)

Response.Write("Radius: ")
Response.Write(disc.Radius)
Response.Write("<br>Diameter: ")
Response.Write(disc.Diameter)
Response.Write("<br>Area: ")
Response.Write(disc.Area)
Response.Write("<br>Circumference: ")
Response.Write(disc.Circumference)
%>
</body>
</html>

This would produce:

read-Only Member Variables

In the previous section, we saw that a constant variable must be initialized when it is created. Although a read-only variable seems to follow the same rule, it doesn't. Remember that you don't need to initialize a read-only variable when you declare it since you can do this in the(a) constructor of the class. Also, because a constructor can be overloaded, a read-only member variable can hold different values depending on the particular constructor that is accessed at a particular time but the value of a constant variable cannot change: it is initialized once, in the class (or in a method) and it keeps that value throughout the class (or method).

 
 
 

Previous Copyright © 2005-2016, FunctionX Next