Polymorphism in VB.NET

In this article I will describe Run time Polymorphism and Compile time polymorphism in VB.NET.
  • 19089
Download Files:
 

Polymorphism:- Polymorphism is one of the crucial features of VB.NET, It means "The ability to take on different form", It is also called as Overloading which means the use of same thing for different purposes. Using Polymorphism we can create as many functions we want with one function name but with different argument list. The function performs different operations based on the argument list in the function call. The exact function to be invoked will be determined by checking the type and number of arguments in the function.
 

Definition:- "Manipulated the object of various classes and invoke method on one object without knowing the object type".

Example:-polymorphism real word examples are Student, Manager, Animal and etc.

Polymorphism can be divide in to two parts, that are given bellow

  • Compile time polymorphism
  • Run time polymorphism
     

Compile time polymorphism:- compile time polymorphism achieved by "Method Overloading", means that same name function with deferent parameters in same class called compile time polymorphism.

Module Module1

Sub Main()
Dim two As New One()
WriteLine(two.add(10))
'calls the function with one argument
WriteLine(two.add(10, 20))
'calls the function with two arguments
WriteLine(two.add(10, 20, 30))
'calls the function with three arguments

End Sub

End Module


Public Class One
Public i, j, k As Integer

Public Function add(ByVal i As Integer) As Integer
'function with one argument
Return i
End Function

Public Function add(ByVal i As Integer, ByVal j As Integer) As Integer
'function with two arguments
Return i + j
End Function

Public Function add(ByVal i As Integer, ByVal j As Integer, ByVal k As Integer) As Integer
'function with three arguments
Return i + j + k
End Function

End Class

Output:10
           20
           30

Run time Polymorphism:-Run time polymorphism achieved by "Method Overriding or Operator Overloading", means that same name function with
same parameters in deferent deferent classes called Run time Polymorphism .

Public Class poly

Public Sub show()
WriteLine("hellow")

End Sub

End Class

Public Class poly2
Inherits poly
Public Sub show()
WriteLine("world")
End Sub

End Class

Class output
Public Shared Sub Main()
Dim a As poly2 = New poly2()
a.show()
End Sub

End Class

Output: World

© 2019 DotNetHeaven. All rights reserved.