Polymorphism using Abstract Classes in Visual Basic.NET 2005 - Defining and implementing abstract classes in Visual Basic 2005: child classes continued (Page 5 of 6 )
Continuing from the previous section, I defined two more sub classes for the super class "Shape" as follows:
Public Class EquiTriangle
Inherits Shape
Public Sub New(ByVal b As Double, ByVal h As Double)
MyBase.New(b, h)
End Sub
Public Overrides Function GetArea() As Double
Return ((1.0 / 2.0) * Me.X * Me.Y)
End Function
End Class
Public Class Square
Inherits Shape
Public Sub New(ByVal s As Double)
MyBase.New(s)
End Sub
Public Overrides Function GetArea() As Double
Return Me.X * Me.X
End Function
End Class
If the developer doesn't implement "GetArea" in any of the classes inherited from the "Shape" class, it would be a compilation error. This is how we can enforce consistency among members of classes belonging to the same group.
Finally, to test the above classes, we can write the code as follows:
Dim r As New Rectangle(10, 20)
Dim s As New Square(20)
Dim t As New EquiTriangle(5, 10)
MessageBox.Show("Area of rectangle: " & r.GetArea)
MessageBox.Show("Area of square: " & s.GetArea)
MessageBox.Show("Area of triangle: " & t.GetArea)
Next: Making use of Polymorphism using abstract classes in Visual Basic 2005 >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee