Overloading and Overriding in Visual Basic.NET 2005

This article gives you an in-depth understanding of the differences between overloading and overriding in Visual Basic.NET 2005. It is assumed that the reader knows something about object-oriented programming in Visual Basic.NET.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 30
July 30, 2007
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Two downloadable zip files are available for this article, one on overloading and one on overriding.

If you are new to OOP in Visual Basic.NET, I strongly suggest that you go through the following links:

Using Constructors with Object-Oriented Database Development

Properties and Object-Oriented Database Development

Using Methods with Object-Oriented Database Development

An Introduction to Object-Oriented Database Development

The entire source code for this article is available in the form of downloadable zip files.  The solution was developed using Microsoft Visual Studio 2005 Professional Edition on Microsoft Windows Server 2003 Enterprise Edition.  I didn't really test it in any other environment.  I request that you post in the discussion area if you have any problems in execution.

A sample class without overloading

Before taking a direct look at overloading, let us try to understand the following class:

Public Class Sample

  Private _x As Double

  Private _y As Double

 

  Public Property X() As Double

    Get

      Return _x

    End Get

    Set(ByVal value As Double)

      _x = value

    End Set

  End Property

 

  Public Property Y() As Double

    Get

      Return _y

    End Get

    Set(ByVal value As Double)

      _y = value

    End Set

  End Property

 

  Public Sub SetTwoValues(ByVal a As Double, ByVal b As Double)

    _x = a

    _y = b

  End Sub

 

  Public Sub SetSingleValue(ByVal a As Double)

    _x = a

    _y = a

  End Sub

 

  Public Function GetProduct() As Double

    Return _x * _y

  End Function

 

End Class

The above class has two private fields ("_x" and "_y") which are only accessible within the class (and not outside the class).  Further, it has two public properties and three public methods (public members are accessible even outside the class).

The following is the sample code needed to test the above sample class:

Dim obj As New Sample

obj.X = 5

obj.Y = 30

MessageBox.Show("Product = " & obj.GetProduct())

 

Dim obj2 As New Sample

obj2.SetTwoValues(10, 20)

MessageBox.Show("Product = " & obj2.GetProduct())

 

Dim obj3 As New Sample

obj3.SetSingleValue(10)

MessageBox.Show("Product = " & obj3.GetProduct())

I created three objects (or instances) for the class "Sample" named "obj," "obj2" and "obj3."  The first object uses properties to assign values.  The second object uses a method named "SetTwoValues" to assign two values.  The third object uses another method named "SetSingleValue" to assign only a single value.

A sample class with method overloading

When we have ten parameters to pass, with different combinations, to methods which have similar logic, naming those methods differently from each other would be confusing when working with objects.  In such a situation, we can implement more methods with the same name and with a difference in parameters.

A rewrite of the class in the previous section, which implements overloading (more methods with the same name and different parameters) is as follows:

Public Class Sample2

  Private _x As Double

  Private _y As Double

 

  Public Property X() As Double

    Get

      Return _x

    End Get

    Set(ByVal value As Double)

      _x = value

    End Set

  End Property

 

  Public Property Y() As Double

    Get

      Return _y

    End Get

    Set(ByVal value As Double)

      _y = value

    End Set

  End Property

 

  Public Sub SetValues(ByVal a As Double, ByVal b As Double)

    _x = a

    _y = b

  End Sub

 

  Public Sub SetValues(ByVal a As Double)

    _x = a

    _y = a

  End Sub

 

  Public Function GetProduct() As Double

    Return _x * _y

  End Function

 

End Class

As you can see, for the above class there exist two methods with the same name, "SetValues," but with different parameters.  Those are called overloaded methods. The following is the code that tests the above class:

    Dim obj As New Sample2

    obj.X = 5

    obj.Y = 30

    MessageBox.Show("Product = " & obj.GetProduct())

 

    Dim obj2 As New Sample2

    obj2.SetValues(10, 20)

    MessageBox.Show("Product = " & obj2.GetProduct())

 

    Dim obj3 As New Sample2

    obj3.SetValues(10)

    MessageBox.Show("Product = " & obj3.GetProduct())

If you observe the "obj2" and "obj3," we are calling the same "SetValues" method.  Based on the number of parameters, and based on their data types, we are passing to the method; the respective method with the best match gets picked up and executed automatically.

A sample class with constructor overloading

Overloading is not limited only to methods. We can even overload constructors, properties, and so forth. The following is a rewrite of the above class which includes both method and constructor overloading:

Public Class Sample3

  Private _x As Double

  Private _y As Double

 

  Public Sub New()

 

  End Sub

 

  Public Sub New(ByVal a As Double)

    _x = a

    _y = a

    'Me.SetValues(a)

  End Sub

 

  Public Sub New(ByVal a As Double, ByVal b As Double)

    _x = a

    _y = b

    'Me.SetValues(a, b)

  End Sub

 

  Public Property X() As Double

    Get

      Return _x

    End Get

    Set(ByVal value As Double)

      _x = value

    End Set

  End Property

 

  Public Property Y() As Double

    Get

      Return _y

    End Get

    Set(ByVal value As Double)

      _y = value

    End Set

  End Property

 

  Public Sub SetValues(ByVal a As Double, ByVal b As Double)

    _x = a

    _y = b

  End Sub

 

  Public Sub SetValues(ByVal a As Double)

    _x = a

    _y = a

  End Sub

 

  Public Function GetProduct() As Double

    Return _x * _y

  End Function

 

End Class

As you can see from the comments in the above class, I am trying to call overloaded methods from overloaded constructors, which is possible.

The following is the code to test the constructors in the above class:

Dim obj As New Sample3(10, 20)

MessageBox.Show("Product = " & obj.GetProduct())

 

Dim obj2 As New Sample3(10)

MessageBox.Show("Product = " & obj.GetProduct())

Method overriding in Visual Basic 2005

In all of the previous sections, we worked with only "overloading."  This section focuses on "overriding." 

Before proceeding further, please note that there is no relationship or similarity between "overloading" and "overriding." They are completely different. To demonstrate "overriding," one needs to work with inheritance. If you are new to inheritance in Visual Basic.NET, I strongly suggest that you go through the following article:

Inheritance with VB.NET 2005

Let us start with defining two simple classes as follows:

Public Class Parent

  Public Sub DispMsg()

    MessageBox.Show("From Parent")

  End Sub

End Class

 

Public Class Child

  Inherits Parent

  Public Sub DispMsg()

    MessageBox.Show("From child")

  End Sub

End Class

From the above, we have two classes, "Parent" and "Child."  The "Child" class gets inherited from the "Parent" class.  The parent class has a method named "DispMsg," and the same method is redefined in the child with the same name.

If we create a parent object (instance), we will have only one method and we can call it without any problem. But if we create a child object, we will have two methods -- one inherited from the parent -- with the same name and signature. Thus the program gives out a warning and defaults to the child method whenever "DispMsg" is called from the child object.

To eliminate this warning, we should either "override" or "shadow" the parent (or inherited) method.  I shall cover the "shadow" technique in my upcoming articles.  For now, let us concentrate on the "override" technique.

The following are the modifications to the previous classes which are needed to implement overriding:

Public Class Parent

  Public Overridable Sub DispMsg()

    MessageBox.Show("From Parent")

  End Sub

End Class

 

Public Class Child

  Inherits Parent

  Public Overrides Sub DispMsg()

    MessageBox.Show("From child")

  End Sub

End Class

To override (or redefine) an inherited method in the child class, the same method must be declared with "overridable" in the parent and with "overrides" in the child. To test the above classes, you can use the following code:

Dim objP As New Parent

objP.DispMsg() 'displays "From Parent"

 

Dim obj As New Child

obj.DispMsg() 'displayes "From Child"

Please note that even if you use a parent reference with the child object, the result would be the same as accessing the child member.  Try testing it out using the following:

CType(obj, Parent).DispMsg()'displayes "From Child"

DirectCast(obj, Parent).DispMsg()'displayes "From Child"

Dim RefParent As Parent = obj

RefParent.DispMsg()'displayes "From Child"

Multi-level method overriding in Visual Basic 2005 inheritance

In the previous section, I covered the meaning of overriding.  In this section, I shall extend the same concept further to multi-level inheritance and overriding in Visual Basic 2005.

Let us redefine our classes as follows:

Public Class Parent

  Public Overridable Sub DispMsg()

    MessageBox.Show("From Parent")

  End Sub

End Class

 

Public Class Child

  Inherits Parent

  Public Overrides Sub DispMsg()

    MessageBox.Show("From child")

  End Sub

End Class

 

Public Class GrandChild

  Inherits Child

  Public Overrides Sub DispMsg()

    MessageBox.Show("From grand child")

  End Sub

End Class

If you observe the above code, I defined three classes with multi-level inheritance (child inherited from parent and grandchild inherited from child).  You can still see that the same "DispMsg" method is defined in all of the classes. 

If a method is defined with "overridable" in the parent, it can be overridden in child classes using "overrides."  If a class has a method already defined with "overrides," it is implicitly declared as "overridable" and we need not define both "overrides" and "overridable" at the same time.

To test the above code, simply create an object based on the "GrandChild" class and try to call "DispMsg" as shown:

Dim obj As New GrandChild

obj.DispMsg() 'displays "From grant child"

Even in this case, if you try to convert the "GrandChild" object to any of its parent or grandparent classes and access the "DispMsg" method, you will receive the same output.

In my next article, I shall introduce "shadows."  I hope you enjoyed the article and any suggestions, bugs, errors, enhancements etc. are highly appreciated at http://jagchat.spaces.live.com

blog comments powered by Disqus
VISUAL BASIC.NET ARTICLES

- Basic Form Properties and Modality in VB.NET
- Multiple Document Interfaces in Visual Basic
- Visual Basic for Beginners
- ASP.NET Image to PDF with VB.Net
- MySQL in ASP.NET: Mono using VB.NET
- AsyncFileUpload File Type and File Size Vali...
- Visual Studio: Adding Functionality and Style
- Clocks and Countdowns
- User-defined Functions using Visual Basic Ap...
- Understanding Object Binding in VBA
- Mastering the Message Box
- Testing a Windows Forms Application
- Using Visual Basic.NET Features to Code a Wi...
- Correcting Code in a Windows Forms Applicati...
- Write Readable Code and Comments for Windows...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 6 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials