VB.NET Polymorphism

  • Polymorphism is the ability for classes to provide different implementation to the method that are called by same name.
  • Polymorphism is a generic term that means 'many shapes'. In VB.NET the simplest form of Polymorphism is overloading of functions and operators. This is known as function overloading and operator overloading respectively.
  • Polymorphism is a way to define the several same name methods in a class. It is called as polymorphism.
  • When we define two or more same name functions with different parameters or with different return type in same class then it is called as function overloading.
  • When we define two or more same name functions with same arguments and same return type in different classes then it is called as function overriding or method overriding.
  • The following diagram shows the polymorphism:
  • polymorphism

Method overriding

When we define any method with same name, same return type and with same arguments in the base class and child class then it is called as method overriding. When we implement this concept then we cannot guess which method will execute at the runtime because method names are same. The following figure shows this concept:


polymorphism

The example of method overriding is as follows:


Module Module1

Class Parent

Public Overridable Sub show()
Console.WriteLine("Parent class")

End Sub
End Class

Class Child : Inherits Parent

Public Overrides Sub show()
Console.WriteLine("Child class")

End Sub
End Class
Sub Main()
Dim c As Child = New Child()
c.show()
Console.ReadKey()
End Sub

End Module

In the above example we have two classes Parent and Child. In both classes we have implemented same method. Here class Child extends the Parent class. Here when execution will starts from the main() function then here we have created object of the Child class and we are calling the show() method. Here Child class can call the Parent class methods by using the object. The output is as follows:

polymorphism