Implementing Polymorphism in VB.NET

In this article you will learn how to implement polymorphism in VB.NET.
  • 2134

In this article I will explain and extends the know-how of implementing polymorphism in VB.Net.  Of course, polymorphism is a huge topic and I will only focus on the little known VB.Net keyword MyClass.

I will replicate the exact same code, as first published in the original tip, and I will place the keyword in the appropriate place.

Lets see some code below:

    Class Parent

        Public Overridable Sub p1()

            Console.Write("Parent.p1")

        End Sub

        Public Sub p2()

            MyClass.p1()

            'Implementing keyword MyClass here tells all derived classes to refer to the base / abstract class wherein the keyword MyClass appears

        End Sub

    End Class

 

    Class Child

        Inherits Parent

        Public Overrides Sub p1()

            Console.Write("Child.p1")

            MyBase.p2()

        End Sub

    End Class

 

    Sub Main()

        Dim p As Parent

        Dim c As Child

        p = New Parent()

        p.p1() 'OK

        p.p2() 'OK

        p = New Child()

        p.p1() 'stack overflow error is prevented

The pitfall comes when you have an instance of class Child and call procedures p1 and p2. Calling p1 produces the following execution flow:

Child.p1 -> Parent.p2 -> Child.p1 -> Parent.p2 -> Child.p1 -> etc.

And the cycle repeats until we have no stack space left. Calling p2 produces the following execution flow:

Child.p2 -> Child.p1 -> Parent.p2 -> Child.p1 -> Parent.p2 -> Child.p1 -> etc.

Implementing the keyword MyClass in the base class tells all derived classes to use the method in the base class itself and, therefore, a stack overflow error is prevented.

        p.p2() 'stack overflow error is prevented

        c = New Child()

        c.p1() 'stack overflow error is prevented

        c.p2() 'stack overflow error is prevented

    End Sub

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.