Home

Inheritance

 

Introduction to Inheritance

 

Definition

Imagine you create a class used to process calculations for a circle. The class may appear as follows:

Imports System

Class Circle
    Public Radius As Double

    Public Function CalculateDiameter() As Double
        Return Radius * 2
    End Function

    Public Function CalculateCircmuference() As Double
        Return CalculateDiameter() * 3.14159
    End Function

    Public Function CalculateArea() As Double
        Return Radius * Radius * 3.14159
    End Function
End Class

Class Exercise
    Public Shared Sub Main()
        Dim circ As Circle = New Circle
        circ.Radius = 25.84

        Console.WriteLine(" -=- Circle Characteristics -=-")
        Console.WriteLine("Radius:        {0} ", circ.Radius)
        Console.WriteLine("Diameter:      {0} ", circ.CalculateDiameter())
        Console.WriteLine("Circmuference: {0} ", circ.CalculateCircmuference())
        Console.WriteLine("Area:          {0} " & vbCrLf, circ.CalculateArea())
    End Sub

End Class

This would produce:

-=- Circle Characteristics -=-
Radius:             25.55
Diameter:         51.1
Circmuference: 160.535249
Area:                2050.837805975

After creating this class, imagine you want to create another class used to process a sphere. You may start thinking of creating a new class and redefining the members similar to those that belong to the above Circle class. To make this easier, you may just select the code of the Circle class, copy it, and then paste it in your document. Fortunately, when a class hold a foundation that another class can use, you can create the new class that is based on the old one: this is the foundation of class inheritance, or simply called inheritance.

Inheritance is the process of creating a new class that is based on an existing class.

 

Class Derivation

As you may have guessed, in order to implement inheritance, you must first have a class that provides the fundamental definition or behavior you need. There is nothing magical about such a class. It could appear exactly like any of the classes we have used so far.

The above Circle class is used to process a circle. It can request or provide a radius. It can also calculate the circumference and the area of a circle. Since a sphere is primarily a 3-dimensional circle, and if you have a class for a circle already, you can simply create your sphere class that uses the already implemented behavior of a circle class.

Creating a class that is based on another class is also referred to as deriving a class from another. The first class serves as parent or base. The class that is based on another class is also referred to as child or derived. To create a class based on another, you use the following formula:

Class Child 
      Inherits Parent

      ' Body of the new class

End Class

In this formula, you start with the Class keyword, followed by a name for your new class, followed by an end of line. On the next line, type the Inherits keyword, followed by the name of the class on which the new Child class would be based. Of course, the Parent class must have been defined; that is, the compiler must be able to find its definition. Based on the above formula, you can create a sphere class based on the earlier mentioned Circle class as follows:

Imports System

Module Exercise

    Class Circle
        
    End Class

    Class Sphere
        Inherits Circle

    End Class

End Module

As mentioned in the previous lesson, if you want to be able to access the class from other languages, you can precede its name with the Public keyword:

Imports System

Public Class Circle

End Class

Public Class Sphere
    Inherits Circle

End Class

Class Exercise

    Public Shared Sub main()

    End Sub

End Class

Otherwise, if you intend to use it only in the current project, you can precede the Class of the class' name with the Private keyword.

 
 

Characteristics of Inheritance

 

Private Members

After deriving a class, it becomes available and you can use it just as you would any other class. Here is an example:

Imports System

Public Class Circle

End Class

Public Class Sphere
    Inherits Circle

End Class

Class Exercise

    Public Shared Sub main()

        Dim ball As Sphere = New Sphere

    End Sub

End Class

When a class is based on another class, all public members of the parent class are made available to the derived class that can use them as necessary. While other methods and classes can also use the public members of a class, the difference is that the derived class can call the public members of the parent as if they belonged to the derived class. That is, the child class doesn't have to "qualify" the public members of the parent class when these public members are used in the body of the derived class. This is illustrated in the following program:

Imports System

Public Class Circle

    Public Radius As Double

    Public Function CalculateDiameter() As Double
        Return Radius * 2
    End Function

    Public Function CalculateCircumference() As Double
        Return CalculateDiameter() * 3.14159
    End Function

End Class

Public Class Sphere
    Inherits Circle

    Public Sub ShowCharacteristics()
        ' Because Sphere is based on Circle, you can access
        ' any public member(s) of Circle without qualifying it(them)
        Radius = 35.84

        Console.WriteLine("Circle Characteristics")
        Console.WriteLine("=======================================================")
        Console.WriteLine("Radius:             {0}", Radius)
        Console.WriteLine("Diameter:         {0}", CalculateDiameter())
        Console.WriteLine("Circumference: {0}", CalculateCircumference())
        Console.WriteLine("=======================================================")
    End Sub

End Class

Class Exercise

    Public Shared Sub main()

        Dim ball As Sphere = New Sphere

        ball.ShowCharacteristics()

    End Sub

End Class

This would produce:

Sphere Characteristics
Radius:        35.84
Diameter:      71.68
Circumference: 225.1891712

Based on the relationship between a child class and its parent, you can use Me in the child to access the public members of the parent class. Here is an example:

Imports System

Public Class Circle

    Public Radius As Double

    Public Function CalculateDiameter() As Double
        Return Radius * 2
    End Function

    Public Function CalculateCircumference() As Double
        Return CalculateDiameter() * 3.14159
    End Function

End Class

Public Class Sphere
    Inherits Circle

    Public Sub ShowCharacteristics()
        ' Because Sphere is based on Circle, you can access
        ' any public member(s) of Circle without qualifying it(them)
        Me.Radius = 35.84

        Console.WriteLine("Circle Characteristics")
        Console.WriteLine("=======================================================")
        Console.WriteLine("Radius:             {0}", Me.Radius)
        Console.WriteLine("Diameter:         {0}", Me.CalculateDiameter())
        Console.WriteLine("Circumference: {0}", Me.CalculateCircumference())
        Console.WriteLine("=======================================================")
    End Sub

End Class

Class Exercise

    Public Shared Sub main()

        Dim ball As Sphere = New Sphere

        ball.ShowCharacteristics()

    End Sub

End Class

We mentioned that, when deriving a new class based on an existing one, all public members of the parent class are accessible to its child classes. In fact, those public members are also available to all other non-child classes and external procedures of the parent class. On the other hand, when creating a class, if you think that a certain member would not need to be accessed outside of the class, you should make it private by starting it with the Private keyword. Here is an example:

Imports System

Public Class Circle

    Public Radius As Double

    Private Function ShowDescription()
        Return "A circle is a round geometric shape constructed " & _
               "so that all considered points of the shape are " & _
               "at an equal distance from a common point called " & _
               "the center. Also, two equally opposite points from " & _
               "the center are at the exact same dictance from that center."
    End Function

    Public Function CalculateDiameter() As Double
        Return Radius * 2
    End Function

    Public Function CalculateCircumference() As Double
        Return CalculateDiameter() * 3.14159
    End Function

End Class

After creating a class, its private members are not accessible to clients of the class, not even to the children of that class. If you attempt to access a private member of a class outside of that class, you would receive an error. That what would happen with the following program:

Imports System

Public Class Circle

    Public Radius As Double

    Private Function ShowDescription()
        Return "A circle is a round geometric shape constructed " & _
               "so that all considered points of the shape are " & _
               "at an equal distance from a common point called " & _
               "the center. Also, two equally opposite points from " & _
               "the center are at the exact same dictance from that center."
    End Function

    Public Function CalculateDiameter() As Double
        Return Radius * 2
    End Function

    Public Function CalculateCircumference() As Double
        Return CalculateDiameter() * 3.14159
    End Function

End Class

Public Class Sphere
    Inherits Circle

    Public Sub ShowCharacteristics()
        ' Because Sphere is based on Circle, you can access
        ' any public member(s) of Circle without qualifying it(them)
        Me.Radius = 35.84

        Console.WriteLine("Circle Characteristics")
        Console.WriteLine("=======================================================")
        Console.WriteLine("Description:      {0} ", ShowDescription())
        Console.WriteLine("Radius:             {0}", Me.Radius)
        Console.WriteLine("Diameter:         {0}", Me.CalculateDiameter())
        Console.WriteLine("Circumference: {0}", Me.CalculateCircumference())
        Console.WriteLine("=======================================================")
    End Sub

End Class

Class Exercise

    Public Shared Sub main()

        Dim ball As Sphere = New Sphere

        ball.ShowCharacteristics()

    End Sub

End Class

 

 

Protected Members

When creating a class that would be used as the base of other classes, in some cases, you may want to create a special relationship among a class and its eventual children. For example, you may want to create some members of the parent class that only its derived class can access. These types of members must be created with the Protected keyword. Here is an example:

Public Class Circle

    Protected Radius As Double

    Private Function ShowDescription()
        Return "A circle is a round geometric shape constructed " & _
               "so that all considered points of the shape are " & _
               "at an equal distance from a common point called " & _
               "the center. Also, two equally opposite points from " & _
               "the center are at the exact same dictance from that center."
    End Function

    Public Function CalculateDiameter() As Double
        Return Radius * 2
    End Function

    Public Function CalculateCircumference() As Double
        Return CalculateDiameter() * 3.14159
    End Function

End Class

Not just the member variables but you can also created methods as protected as long as you intend it only for the class and its children. Remember that a protected member cannot be accessed by the clients of the class, only by the class itself and its children.

When accessing the protected members of a class from its children, you can use Me to locate those members: Me gives you access to non-Shared public and protected members of both the parent(s) and its class. Here is an example:

Imports System

Public Class Circle

    Protected Radius As Double

    Protected Function ShowDescription()
        Return "A circle is a round geometric shape " & vbCrLf & _
               "constructed so that all considered points of the " & vbCrLf & _
               "shape are at an equal distance from a common point " & vbCrLf & _
               "called the center. Also, two equally opposite points " & vbCrLf & _
               "from the center are at the exact same dictance from " & vbCrLf & _
               "that center."
    End Function

    Public Function CalculateDiameter() As Double
        Return Radius * 2
    End Function

    Public Function CalculateCircumference() As Double
        Return CalculateDiameter() * 3.14159
    End Function

End Class

Public Class Sphere
    Inherits Circle

    Public Sub ShowCharacteristics()
        ' Because Sphere is based on Circle, you can access
        ' any public member(s) of Circle without qualifying it(them)
        Me.Radius = 35.84

        Console.WriteLine("Circle Characteristics")
        Console.WriteLine("=======================================================")
        Console.WriteLine("Description:   {0}", Me.ShowDescription())
        Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-")
        Console.WriteLine("Radius:        {0}", Me.Radius)
        Console.WriteLine("Diameter:      {0}", Me.CalculateDiameter())
        Console.WriteLine("Circumference: {0}", Me.CalculateCircumference())
        Console.WriteLine("=======================================================")
    End Sub

End Class

Class Exercise

    Public Shared Sub main()

        Dim ball As Sphere = New Sphere

        ball.ShowCharacteristics()

    End Sub

End Class

 

Home

Polymorphism

 

Introduction

As mentioned already, inheritance allows you to reuse, in a child class, code that is already implemented in a parent class. In some cases, that original code will be enough. In some other cases, you will need to apply new behavior to a child class even though the parent class already has a behavior close to what you seek. Re-creating a method in a child class using the same signature (name and arguments, if any) of a method of a parent class is referred to as overriding. Based on this, if a derived and a parent classes have the same member but implemented differently, when accessing that in your code, you need to know what particular member you are referring to, the parent or the derived's. This is the basis of polymorphism.

Overriding a Method

When creating the above two classes, imagine that you want to create a method that displays the characteristics of each shape. The method would belong to its corresponding class. This can be done as follows:

Imports System

Public Class Circle

    Protected Radius As Double

    Protected Function ShowDescription()
        Return "A circle is a round geometric shape " & vbCrLf & _
               "constructed so that all considered points of the " & vbCrLf & _
               "shape are at an equal distance from a common point " & vbCrLf & _
               "called the center. Also, two equally opposite points " & vbCrLf & _
               "from the center are at the exact same dictance from " & vbCrLf & _
               "that center."
    End Function

    Public Function CalculateDiameter() As Double
        Return Radius * 2
    End Function

    Public Function CalculateCircumference() As Double
        Return CalculateDiameter() * 3.14159
    End Function

    Public Sub ShowCharacteristics()
        Console.WriteLine("Circle Characteristics")
        Console.WriteLine("=======================================================")
        Console.WriteLine("Description:   {0}", Me.ShowDescription())
        Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-")
        Console.WriteLine("Radius:        {0}", Radius)
        Console.WriteLine("Diameter:      {0}", CalculateDiameter())
        Console.WriteLine("Circumference: {0}" & vbCrLf, CalculateCircumference())
    End Sub

End Class

Public Class Sphere
    Inherits Circle

    Public Sub ShowCharacteristics()
        ' Because Sphere is based on Circle, you can access
        ' any public member(s) of Circle without qualifying it(them)

        Console.WriteLine("Sphere Characteristics")
        Console.WriteLine("=======================================================")
        Console.WriteLine("Description:   {0}", Me.ShowDescription())
        Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-")
        Console.WriteLine("Radius:        {0}", Me.Radius)
        Console.WriteLine("Diameter:      {0}", Me.CalculateDiameter())
        Console.WriteLine("Circumference: {0}", Me.CalculateCircumference())
        Console.WriteLine("=======================================================")
    End Sub

End Class

Class Exercise

    Public Shared Sub main()

    End Sub

End Class

When creating a class such as the above circle, if you create a member that the class' children would override, you can (should/must) indicate this to the compiler. This is done by preceding it with the Overridable keyword. This would be done as follows:

Imports System

Module Exercise

    Private Class Circle

        Public Ovirridable Sub ShowCharacteristics()
            
        End Sub
    End Class

    Private Class Sphere
        Inherits Circle

        Public Sub ShowCharacteristics()
            
        End Sub
    End Class

    Public Sub Main()
        
    End Sub

End Module

Once the member has been marked as overridable, when implementing the child class, in order to override it, you must mark the corresponding member of the child class as override. To do this, precede it with the Overrides keyword. This would be done as follows:

Imports System

Public Class Circle

    Protected Radius As Double

    Protected Overridable Function ShowDescription()
        Return "A circle is a round geometric shape " & vbCrLf & _
               "constructed so that all considered points of the " & vbCrLf & _
               "shape are at an equal distance from a common point " & vbCrLf & _
               "called the center. Also, two equally opposite points " & vbCrLf & _
               "from the center are at the exact same dictance from " & vbCrLf & _
               "that center."
    End Function

    Public Function CalculateDiameter() As Double
        Return Radius * 2
    End Function

    Public Function CalculateCircumference() As Double
        Return CalculateDiameter() * 3.14159
    End Function

    Public Overridable Sub ShowCharacteristics()
        Me.Radius = 35.84

        Console.WriteLine("Circle Characteristics")
        Console.WriteLine("=======================================================")
        Console.WriteLine("Description:   {0}", Me.ShowDescription())
        Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-")
        Console.WriteLine("Radius:        {0}", Me.Radius)
        Console.WriteLine("Diameter:      {0}", Me.CalculateDiameter())
        Console.WriteLine("Circumference: {0}" & vbCrLf, Me.CalculateCircumference())
    End Sub

End Class

Public Class Sphere
    Inherits Circle

    Protected Overrides Function ShowDescription()
        Return "A sphere is a three-dimensional geometric " & vbCrLf & _
               "shape based on a circle. It is constructed " & vbCrLf & _
               "so that all considered points around the shape " & vbCrLf & _
               "are at an equal distance from a common point " & vbCrLf & _
               "called the center. Like the circle, two equally " & vbCrLf & _
               "opposite points from the center are at the exact " & vbCrLf & _
               "same dictance from that center."
    End Function

    Public Overrides Sub ShowCharacteristics()
        ' Because Sphere is based on Circle, you can access
        ' any public member(s) of Circle without qualifying it(them)
        Me.Radius = 35.84

        Console.WriteLine("Sphere Characteristics")
        Console.WriteLine("=======================================================")
        Console.WriteLine("Description:   {0}", Me.ShowDescription())
        Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-")
        Console.WriteLine("Radius:        {0}", Me.Radius)
        Console.WriteLine("Diameter:      {0}", Me.CalculateDiameter())
        Console.WriteLine("Circumference: {0}", Me.CalculateCircumference())
        Console.WriteLine("=======================================================")
    End Sub

End Class

Class Exercise

    Public Shared Sub main()
        Dim circ As Circle = New Circle
        circ.ShowCharacteristics()

        Dim ball As Sphere = New Sphere
        ball.ShowCharacteristics()

    End Sub

End Class

This would produce:

Circle Characteristics
=======================================================
Description:   A circle is a round geometric shape
constructed so that all considered points of the
shape are at an equal distance from a common point
called the center. Also, two equally opposite points
from the center are at the exact same dictance from
that center.
-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-
Radius:             35.84
Diameter:         71.68
Circumference: 225.1891712

Sphere Characteristics
=======================================================
Description:   A sphere is a three-dimensional geometric
shape based on a circle. It is constructed
so that all considered points around the shape
are at an equal distance from a common point
called the center. Like the circle, two equally
opposite points from the center are at the exact
same dictance from that center.
-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-
Radius:             35.84
Diameter:         71.68
Circumference: 225.1891712
=======================================================

If you mark as member of a child class with Overrides, it must have a corresponding member in the parent class and that corresponding member must be marked with the Overridable keyword.

 
 

Shadowing a Method

You can notice in the above example that the derived class produces the same results as the base class. In reality, inheritance is used to solve various Object-Oriented Programming (OOP) problems. One of them consists of customizing, adapting, or improving the behavior of a feature of the parent class. For example, although both the circle and the sphere have an area, their areas are not the same. A circle is a flat surface but a sphere is a volume, which makes its area very much higher. Since they use different formulas for their respective area, you should implement a new version of the area in the sphere. This would be done as follows:

Imports System

    Private Class Circle
        Public Radius As Double

        Public Function CalculateArea() As Double
            Return Radius * Radius * 3.14159
        End Function

    End Class

    Private Class Sphere
        Inherits Circle

        Public Function CalculateArea() As Double
            Return 4 * Radius * Radius * 3.14159
        End Function

        End Sub

Class Exercise
    End Class

    Public Sub Main()
        
    End Sub

End Class

Imagine that, in a method of the Sphere class, you call an Area() method, even if you use Me, it may not appear clear what Area() you are accessing. If you create a member, such as a method, in the child class and that has the same signature as an existing member of a parent class, to make sure that you access the derived version of the member, you can hide the corresponding member of the parent class. To do this, precede the member of the child class with the Shadows keyword. This would be done as follows:

Imports System

Public Class Circle

    Protected Radius As Double

    Protected Overridable Function ShowDescription()
        Return "A circle is a round geometric shape " & vbCrLf & _
               "constructed so that all considered points of the " & vbCrLf & _
               "shape are at an equal distance from a common point " & vbCrLf & _
               "called the center. Also, two equally opposite points " & vbCrLf & _
               "from the center are at the exact same dictance from " & vbCrLf & _
               "that center."
    End Function

    Public Function CalculateDiameter() As Double
        Return Radius * 2
    End Function

    Public Function CalculateCircumference() As Double
        Return CalculateDiameter() * 3.14159
    End Function

    Public Function CalculateArea() As Double
        Return Radius * Radius * 3.14159
    End Function

    Public Overridable Sub ShowCharacteristics()
        Me.Radius = 35.84

        Console.WriteLine("Circle Characteristics")
        Console.WriteLine("=======================================================")
        Console.WriteLine("Description:   {0}", Me.ShowDescription())
        Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-")
        Console.WriteLine("Radius:        {0}", Radius)
        Console.WriteLine("Diameter:      {0}", Me.CalculateDiameter())
        Console.WriteLine("Circumference: {0}", Me.CalculateCircumference())
        Console.WriteLine("Area:          {0}", Me.CalculateArea())
        Console.WriteLine("=======================================================")
    End Sub

End Class

Public Class Sphere
    Inherits Circle

    Protected Overrides Function ShowDescription()
        Return "A sphere is a three-dimensional geometric " & vbCrLf & _
               "shape based on a circle. It is constructed " & vbCrLf & _
               "so that all considered points around the shape " & vbCrLf & _
               "are at an equal distance from a common point " & vbCrLf & _
               "called the center. Like the circle, two equally " & vbCrLf & _
               "opposite points from the center are at the exact " & vbCrLf & _
               "same dictance from that center."
    End Function

    Public Shadows Function CalculateArea() As Double
        Return 4 * Radius * Radius * 3.14159
    End Function

    Public Function CalculateVolume() As Double
        Return 4 * 3.14159 * Radius * Radius * Radius / 3
    End Function

    Public Overrides Sub ShowCharacteristics()
        ' Because Sphere is based on Circle, you can access
        ' any public member(s) of Circle without qualifying it(them)
        Me.Radius = 35.84

        Console.WriteLine("Sphere Characteristics")
        Console.WriteLine("=======================================================")
        Console.WriteLine("Description:   {0}", Me.ShowDescription())
        Console.WriteLine("-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-")
        Console.WriteLine("Radius:        {0}", Me.Radius)
        Console.WriteLine("Diameter:      {0}", Me.CalculateDiameter())
        Console.WriteLine("Circumference: {0}", Me.CalculateCircumference())
        Console.WriteLine("Area:          {0}", Me.CalculateArea())
        Console.WriteLine("Volume:        {0}", Me.CalculateVolume())
        Console.WriteLine("=======================================================")
    End Sub

End Class

Class Exercise

    Public Shared Sub main()
        Dim circ As Circle = New Circle
        circ.ShowCharacteristics()

        Dim ball As Sphere = New Sphere
        ball.ShowCharacteristics()

    End Sub

End Class

This would produce:

Circle Characteristics
=======================================================
Description:   A circle is a round geometric shape
constructed so that all considered points of the
shape are at an equal distance from a common point
called the center. Also, two equally opposite points
from the center are at the exact same dictance from
that center.
-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-
Radius:        35.84
Diameter:      71.68
Circumference: 225.1891712
Area:          4035.389947904
=======================================================
Sphere Characteristics
=======================================================
Description:   A sphere is a three-dimensional geometric
shape based on a circle. It is constructed
so that all considered points around the shape
are at an equal distance from a common point
called the center. Like the circle, two equally
opposite points from the center are at the exact
same dictance from that center.
-=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=- -=-
Radius:        35.84
Diameter:      71.68
Circumference: 225.1891712
Area:          16141.559791616
Volume:        192837.834310506
=======================================================
 

Previous Copyright © 2004-2007 Yevol Next

Home

Inheritance and the .NET Framework

 

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 to use in your Visual Basic application, the class is automatically derived from Object. Consider the following Square class:

Imports System

Imports System

 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

    Shared Sub Main()
        Dim sqr As Square = New Square

        Console.Write("Enter Side: ")
        sqr.Side = Double.Parse(Console.ReadLine())

        Console.WriteLine()
        Console.WriteLine("Square Characteristics")
        Console.WriteLine("Side:      {0:F}", sqr.Side)
        Console.WriteLine("Perimeter: {0:F}", sqr.CalculatePerimeter())
        Console.WriteLine("Area:      {0:F}", sqr.CalculateArea())
        Console.WriteLine()
    End Sub

End Class

Here is an example of running the program:

Enter Side: 42.48

Square Characteristics
Side:      42.48
Perimeter: 169.92
Area:      1804.55

Although the Square class doesn't indicate that it is inheriting from any class, by virtue of belonging to a Visual Basic application, it inherits from Object. For this reason, the above code could also have been written as follows:

Imports System

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

    Shared Sub Main()

        Dim sqr As Square = New Square

        Console.Write("Enter Side: ")
        sqr.Side = Double.Parse(Console.ReadLine())

        Console.WriteLine()
        Console.WriteLine("Square Characteristics")
        Console.WriteLine("Side:          {0:F}", sqr.Side)
        Console.WriteLine("Perimeter: {0:F}", sqr.CalculatePerimeter())
        Console.WriteLine("Area:         {0:F}", sqr.CalculateArea())
        Console.WriteLine()
    End Sub

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. The obvious question would be, "What does Object offer to its descendant?". By itself, the Object class provides little but useful functionality to its children. In fact it is equipped with only half a dozen methods. Still, this little functionality allows the various child class to interact easily or perform some operations that would require casting.

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:

Imports System

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

    Shared Sub Main()

        Dim sqr As Square = New Square

        sqr.ToString()
        
    End Sub

End Class

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:

Imports System

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

    Public Overrides Function ToString() As String
        Console.WriteLine("Square Characteristics")
        Console.WriteLine("Side:      {0:F}", Side)
        Console.WriteLine("Perimeter: {0:F}", CalculatePerimeter())
        Console.WriteLine("Area:      {0:F}", CalculateArea())
    End Function

    Shared Sub Main()

        Dim sqr As Square = New Square

        Console.Write("Enter Side: ")
        sqr.Side = Double.Parse(Console.ReadLine())

        Console.WriteLine()
        sqr.ToString()
        Console.WriteLine()
    End Sub

End Class

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:

Imports System

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

    Public Overrides Function ToString() As String
        Console.WriteLine("Square Characteristics")
        Console.WriteLine("Side:      {0:F}", Side)
        Console.WriteLine("Perimeter: {0:F}", CalculatePerimeter())
        Console.WriteLine("Area:      {0:F}", CalculateArea())
    End Function

    Shared Sub Main()

        Dim sqr As Square = New Square

        Console.Write("Enter Side: ")
        sqr.Side = Double.Parse(Console.ReadLine())

        Console.WriteLine("{0}", sqr.ToString())

    End Sub

End Class

 

 

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:

Imports System

Class Exercise

    Public Shared Sub Main()
        Dim number1 As Integer, number2 As Integer

        number1 = 248
        number2 = 2480
        Console.WriteLine("{0} = {1}: {2}", number1, number2, _
                                      number1.Equals(number2))
    End Sub

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:

Imports System

Class Exercise

    Public Shared Sub Main()
        Dim Country As String, Pais As String

        Country = "Senegal"
        Pais = "Senegal"
        Console.WriteLine("{0} = {1}: {2}", Country, Pais, _
                                      Equals(Country, Pais))
    End Sub

End Class

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:

Imports System

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

    Public Overrides Function ToString() As String
        Console.WriteLine("Square Characteristics")
        Console.WriteLine("Side:      {0:F}", Side)
        Console.WriteLine("Perimeter: {0:F}", CalculatePerimeter())
        Console.WriteLine("Area:      {0:F}", CalculateArea())
    End Function

    Shared Sub Main()

        Dim sqr1 As Square = New Square
        Dim sqr2 As Square = New Square

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

        Console.WriteLine()
        Console.WriteLine("{0}", sqr1.ToString())
        Console.WriteLine("{0}", sqr2.ToString())

        Console.WriteLine("Squares Equality: {0}", sqr1.Equals(sqr2))
    End Sub

End Class

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:

Imports System

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

    Public Overrides Function ToString() As String
        Console.WriteLine("Square Characteristics")
        Console.WriteLine("Side:      {0:F}", Side)
        Console.WriteLine("Perimeter: {0:F}", CalculatePerimeter())
        Console.WriteLine("Area:      {0:F}", 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

    Shared Sub Main()

        Dim sqr1 As Square = New Square
        Dim sqr2 As Square = New Square

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

        Console.WriteLine()
        Console.WriteLine("{0}", sqr1.ToString())
        Console.WriteLine("{0}", sqr2.ToString())

        Console.WriteLine("Squares Equality: {0}", sqr1.Equals(sqr2))

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

        Console.WriteLine()
        Console.WriteLine("{0}", sqr1.ToString())
        Console.WriteLine("{0}", sqr2.ToString())

        Console.WriteLine("Squares Equality: {0}", Equals(sqr1, sqr2))
    End Sub

End Class

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.

 

The Current Date

Microsoft Visual Basic provides various functions to perform date and time related operations. These functions allow you to add dates or times, find the difference between dates or times, or add constant values to dates or times.

The current date is represented by a function called Date. The Date() function is used to get the system date of the computer. You can use it to display today's date, provided your computer has the correct date.

The current time of the computer is represented by a function called Time. The Time() function is used to get the system time of the computer.

The Date() and Time() functions can be combined and are represented by a function called Now.

 


Previous Copyright © 2008 Yevol Next