Home

Built-In Classes: Object

  

An Object Variable

An Object can be any type of data that you want to use in your program. In most cases, but sparingly, it can be used to declare a variable of any type. Here are examples:

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
    Dim CountryName As Object
    Dim NumberOfPages As Object
    Dim UnitPrice As Object

    CountryName = "Australia"
    NumberOfPages = 744
    UnitPrice = 248.95

    Response.Write("Country Name: " & CountryName)
    Response.Write("<br>Number of Pages: " & NumberOfPages)
    Response.Write("<br>Unit Price: " & UnitPrice)
%>

</body>
</html>

If you do not specify a data type or cannot figure out what data type you want to use, you can use the Object data type.

To convert a value or an expression to the Object type, you can use CObj().

 

Object: The Ancestor to all Classes

The .NET Framework is the main library used by the Microsoft Visual Basic .NET programming language. When Visual Basic was developed, inheritance was kept in mind art all levels so that the .NET Framework library provides as much functionality as possible to enhance all types of applications necessary. To provide this functionality, the .NET Framework provides a rich set of classes (and namespaces as we will see).

At the highest level, the library provides the Object class that serves as the common ancestor to all classes used in the .NET Framework. In fact, any time you create a class, the class is automatically derived from Object. Consider the following Square class:

Public Class Square
        Public Side As Double

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

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

Although the Square class doesn't indicate that it is inheriting from any class, it inherits from Object. For this reason, the above code could also have been written as follows:

Public Class Square
        Inherits Object


End Class

This would produce the same results. Most of the time, if not always, you don't need to derive a class from Object: this inheritance is automatic and it is implied.

All of the methods of the Object class are public, making them directly available to the descendant classes. Most are "Overridable"s, meaning if you want to use them, you should implement your own version in your class.

String Conversion

One of the functionalities provided by the Object class consists of converting a class to a string. Because this can mean different things to different classes. The Object class provides the method named ToString. Its syntax is:

Public Overridable Function ToString() As String

In some cases, you can directly call this method as it is available to your class already. Here is an example:

Module Exercise
    Public Class Square
        Inherits Object

        Public Side As Double

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

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

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

        sqr.ToString()

        Return 0
    End Function

End Module

Otherwise, most of the time, you will need to indicate to the compiler how this method should be interpreted by your class, which is done by overriding it. To override this method, follow the rules of overriding a method by associating the Overrides keyword with the syntax of the method. In the body of the method, implement it as you see fit. Here is an example:

Module Exercise
    Public Class Square
        Inherits Object

        Public Side As Double

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

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

        Public Overrides Function ToString() As String
            Return "Square Characteristics" & vbCrLf & _
                   "Side:      " & CStr(Side) & vbCrLf & _
                   "Perimeter: " & CStr(CalculatePerimeter()) & vbCrLf & _
                   "Area:      " & CStr(CalculateArea())
        End Function
    End Class

End Module

Because the Object.ToString() method returns a String object, you can assign its result to a string or pass it to a function or method that takes a string as argument. Here is an example:

Module Exercise
    Public Class Square
        Inherits Object

        Public Side As Double

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

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

        Public Overrides Function ToString() As String
            Return "Square Characteristics" & vbCrLf & _
                   "Side:      " & CStr(Side) & vbCrLf & _
                   "Perimeter: " & CStr(CalculatePerimeter()) & vbCrLf & _
                   "Area:      " & CStr(CalculateArea())
        End Function
    End Class

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

        Response.Write(sqr.ToString())

        Return 0
    End Function

End Module
 
 
 

Object and Classes Comparisons

Another valuable method of the Object class is called Equals. This method is used to compare two instances of a class for equality. This method is overloaded with two versions and each returns a Boolean value.

One of the versions of the Object.Equals() method has the following syntax:

Overloads Public Overridable Function Equals(ByVal obj As Object) As Boolean

This method can be called by any class of a .NET Framework application and it takes as argument an instance of the class that the called needs to be compared to. Here is an example:

Module Exercise

    Public Function Main() As Integer
        Dim number1 As Integer, number2 As Integer

        number1 = 248
        number2 = 2480
        Response.Write("{0} = {1}: {2}", number1, number2, _
                                      number1.Equals(number2))

        Return 0
    End Function

End Module

This would produce:

248 = 2480: False

The second version of the Object.Equals() method has the following syntax:

Overloads Public Shared Function Equals(ByVal objA As Object,_
					ByVal objB As Object) As Boolean

This version is declared as Shared. This means that it is not called by a specific instance of a class. Instead, it takes two arguments that each represents an instance of the classes that need to be compared. Here is an example of calling it:

Module Exercise

    Public Function Main() As Integer
        Dim Country As String, Pais As String

        Country = "Senegal"
        Pais = "Senegal"
        Response.Write("{0} = {1}: {2}", Country, Pais, _
                                      Equals(Country, Pais))

        Return 0
    End Function

End Module

This would produce:

Senegal = Senegal: True

Although this method is made available to all .NET classes by through inheritance from the Object class, in most cases, to make sure it rightly behaves, you should customize its implementation in most of your classes where you intend to call it. Consider the following program:

Module Exercise
    Public Class Square
        Inherits Object

        Public Side As Double

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

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

        Public Overrides Function ToString() As String
            Return "Square Characteristics" & vbCrLf & _
                   "Side:      " & CStr(Side) & vbCrLf & _
                   "Perimeter: " & CStr(CalculatePerimeter()) & vbCrLf & _
                   "Area:      " & CStr(CalculateArea())
        End Function
    End Class

    Public Function Main() As Integer
        Dim sqr1 As Square = New Square
        Dim sqr2 As Square = New Square

        Response.Write(" =+= First Square =+=")
        Console.Write("Enter Side: ")
        sqr1.Side = Double.Parse(Console.ReadLine())
        Response.Write(" =+= Second Square =+=")
        Console.Write("Enter Side: ")
        sqr2.Side = Double.Parse(Console.ReadLine())

        Response.Write()
        Response.Write("" & sqr1.ToString())
        Response.Write()
        Response.Write("" & sqr2.ToString())
        Response.Write()

        Response.Write("Squares Equality: " & sqr1.Equals(sqr2))

        Return 0
    End Function

End Module

Here is an example of executing it:

=+= First Square =+=
Enter Side: 125.84
 =+= Second Square =+=
Enter Side: 125.84

Square Characteristics
Side:      125.84
Perimeter: 503.36
Area:      15835.71

Square Characteristics
Side:      125.84
Perimeter: 503.36
Area:      15835.71

Squares Equality: False

Notice that, although both square instances have the same Side value and produce the same area, the compiler renders them not equal. This is an indication that the compiler doesn't know how to compare two instances of the Square class. The solution to this type of problem is to override the Equals() method in your class instead of relying on the default implementation from the Object class. Here are two overrides of the Equals() methods as overridden for the above Square class:

Module Exercise
    Public Class Square
        Inherits Object

        Public Side As Double

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

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

        Public Overrides Function ToString() As String
            Return "Square Characteristics" & vbCrLf & _
                   "Side:      " & CStr(Side) & vbCrLf & _
                   "Perimeter: " & CStr(CalculatePerimeter()) & vbCrLf & _
                   "Area:      " & CStr(CalculateArea())
        End Function

        Public Overridable Overloads Function Equals(ByVal sqr As Square) As Boolean
            ' We will only compare the side of the square
            ' because the calculations of the perimeter and the area
            ' directly depend on the side
            ' If the side of the square passed as argument is equal
            ' to the side of this object, both objects are equal
            If sqr.Side = Me.Side Then Return True
            ' If the sides are not equal, then the objects are not equal
            Return False
        End Function

        Public Overloads Shared Function Equals(ByVal first As Square, _
                                                ByVal second As Square) As Boolean
            ' We will only compare the side of the square
            ' If the side of the first square is equal
            ' to the side of the second one, then both squares are equal
            If first.Side = second.Side Then Return True
            ' If the sides are not equal, then the objects are not equal
            Return False
        End Function
    End Class

    Public Function Main() As Integer
        Dim sqr1 As Square = New Square
        Dim sqr2 As Square = New Square

        Response.Write(" =+= First Square =+=")
        Console.Write("Enter Side: ")
        sqr1.Side = Double.Parse(Console.ReadLine())
        Response.Write(" =+= Second Square =+=")
        Console.Write("Enter Side: ")
        sqr2.Side = Double.Parse(Console.ReadLine())

        Response.Write()
        Response.Write("" & sqr1.ToString())
        Response.Write("" & sqr2.ToString())

        Response.Write("Squares Equality: " & sqr1.Equals(sqr2))

        Response.Write()
        Response.Write(" =+= First Square =+=")
        Console.Write("Enter Side: ")
        sqr1.Side = Double.Parse(Console.ReadLine())
        Response.Write(" =+= Second Square =+=")
        Console.Write("Enter Side: ")
        sqr2.Side = Double.Parse(Console.ReadLine())

        Response.Write()
        Response.Write("" & sqr1.ToString())
        Response.Write()
        Response.Write("" & sqr2.ToString())
        Response.Write()

        Response.Write("Squares Equality: " & Equals(sqr1, sqr2))

        Return 0
    End Function

End Module

Here is an example of testing the program:

=+= First Square =+=
Enter Side: 125.84
 =+= Second Square =+=
Enter Side: 125.84

Square Characteristics
Side:      125.84
Perimeter: 503.36
Area:      15835.71

Square Characteristics
Side:      125.84
Perimeter: 503.36
Area:      15835.71

Squares Equality: True

 =+= First Square =+=
Enter Side: 38.45
 =+= Second Square =+=
Enter Side: 16.82

Square Characteristics
Side:      38.45
Perimeter: 153.80
Area:      1478.40

Square Characteristics
Side:      16.82
Perimeter: 67.28
Area:      282.91

Squares Equality: False

Here is another run of the same program:

=+= First Square =+=
Enter Side: 70.68
 =+= Second Square =+=
Enter Side: 42.04

Square Characteristics
Side:      70.68
Perimeter: 282.72
Area:      4995.66

Square Characteristics
Side:      42.04
Perimeter: 168.16
Area:      1767.36

Squares Equality: False

 =+= First Square =+=
Enter Side: 58.26
 =+= Second Square =+=
Enter Side: 58.26

Square Characteristics
Side:      58.26
Perimeter: 233.04
Area:      3394.23

Square Characteristics
Side:      58.26
Perimeter: 233.04
Area:      3394.23

Squares Equality: True

Notice that, this time, the compiler knows how to perform the comparison of two Square objects using either version of the Equals() method.

 
 
   
 

Home Copyright 2008-2009 FunctionX, Inc.