METHOD OVERLOADING :
Method Overloading allows us to write different versions of a method (i.e. a
single class can contain more than one methods (Sub / Functions) of same name
but of different implementation). And compiler will automatically select the
appropriate method based on parameters passed.
Consider following points in order to implement/understand method overloading
:
All the overloaded methods must be of same procedure type (either only Sub
or only Function).
Allowed :
Public
Overloads Function
add(ByVal a As
Integer, ByVal b
As Integer)
Public
Overloads Function
add(ByVal a As
Long, ByVal b
As Long)
Not Allowed :
Public
Overloads Function
add(ByVal a As
Integer, ByVal b
As Integer)
Public
Overloads Sub
add(ByVal a As
Long, ByVal
b As Long)
Don't repeat same parameters with same data types in parameter, it will show
an error
Example :
Public
Overloads Function
add(ByVal a As
Integer, ByVal b
As Integer)
Public
Overloads Function
add(ByVal a As
Integer, ByVal b
As Integer)
Overloaded methods must have different number parameters and/or Different data
types in the parameters
Different number of parameters
Public
Overloads Function
add(ByVal a As
Integer, ByVal b
As Integer)
Public
Overloads Function
add(ByVal a As
Integer, ByVal b
As Integer,
ByVal c As
Integer)
Different data type in parameters
Public
Overloads Function
add(ByVal a As
Integer, ByVal b
As Integer)
Public
Overloads Function
add(ByVal a As
Long, ByVal b
As Long)
Inherited Classes can also overload their own methods or their base class
methods
Example 1 :
Imports System.Console
Module
Module1
Public Class
demo
Public
Overloads Function add(ByVal
a As Integer,
ByVal b As
Integer)
WriteLine("You are in function
add(integer, integer)")
Return a + b
End
Function
Public
Overloads Function add(ByVal
a As Long,
ByVal b As
Long)
WriteLine("You are in function add(long,
long)")
Return a + b
End
Function
End
Class
Sub Main()
Dim obj As
New
demo
WriteLine(obj.add(2147483640, 4))
WriteLine(obj.add(2147483648, 1))
WriteLine("press return to exit...")
Read()
End
Sub
End
Module
Output :
![MethodOverloading1.gif]()
Example 2 :
Imports System.Console
Module
Module1
Public Class
demo
Public
Overloads Function add(ByVal
a As Integer,
ByVal b As
Integer)
WriteLine("You are in function add(a,b)")
Return a + b
End
Function
Public
Overloads Function add(ByVal
a As Integer,
ByVal b As
Integer, ByVal c
As Integer)
WriteLine("You are in function add(a, b,
c)")
Return a + b + c
End
Function
End
Class
Sub Main()
Dim obj As
New
demo
WriteLine(obj.add(4, 2))
WriteLine(obj.add(4, 5, 1))
WriteLine("press return to exit...")
Read()
End
Sub
End
Module
Output :
![MethodOverloading2.gif]()