Polymorphism in Visual Basic
Overview
Polymorphism allows objects to be treated as instances of their base type while still exhibiting behavior defined by their derived types. In Visual Basic, polymorphism is achieved through inheritance, Overrides
, Overloads
, and the Implements
keyword.
Key Concepts
- Late Binding – Determined at runtime using
Object
orDynamic
types. - Early Binding – Determined at compile time through inheritance hierarchies.
- Method Overriding – Derived class provides a new implementation of a base class method using
Overrides
. - Method Overloading – Multiple methods with the same name but different signatures using
Overloads
.
Example: Method Overriding
Public Class Animal
Public Overridable Sub Speak()
Console.WriteLine("The animal makes a sound.")
End Sub
End Class
Public Class Dog
Inherits Animal
Public Overrides Sub Speak()
Console.WriteLine("Woof!")
End Sub
End Class
Module Program
Sub Main()
Dim a As Animal = New Dog()
a.Speak() ' Outputs: Woof!
End Sub
End Module
Example: Method Overloading
Public Class Calculator
Public Overloads Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
Public Overloads Function Add(a As Double, b As Double) As Double
Return a + b
End Function
End Class
Module Demo
Sub Main()
Dim calc As New Calculator()
Console.WriteLine(calc.Add(3, 4)) ' Integer result: 7
Console.WriteLine(calc.Add(2.5, 3.1)) ' Double result: 5.6
End Sub
End Module
Interface Implementation
Implementing an interface provides another form of polymorphism. Objects that implement the same interface can be used interchangeably.
Public Interface IShape
Function Area() As Double
End Interface
Public Class Circle
Implements IShape
Private ReadOnly _radius As Double
Public Sub New(radius As Double)
_radius = radius
End Sub
Public Function Area() As Double Implements IShape.Area
Return Math.PI * _radius * _radius
End Function
End Class
Public Class Rectangle
Implements IShape
Private ReadOnly _width As Double
Private ReadOnly _height As Double
Public Sub New(width As Double, height As Double)
_width = width
_height = height
End Sub
Public Function Area() As Double Implements IShape.Area
Return _width * _height
End Function
End Class
Module ShapesDemo
Sub Main()
Dim shapes As IShape() = {New Circle(3), New Rectangle(4, 5)}
For Each s In shapes
Console.WriteLine(s.Area())
Next
End Sub
End Module