Emailid
Password
         
  
    Forgot password

New user Sign Up


Applying Polymorphism in VB.Net

       Current Rating:  40%                                                     Total Members Rated:  1
                                                                     Send To Friend

  

Applying Polymorphism in VB.Net

 

This article inspires you how to take advantage of polymorphism in VB.Net. This article stresses that polymorphism can lead to nightmares and headaches. And this problem can be solved with the VB.Net keyword called My Class.

 

Notice the code:

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

My class has to apply here. If it is not so, a stack overflow error is shown.

Parent.p2() calls Parent.p1()

Parent.p1() is polymorphic because it can be overridden

Child.p1() overrides Parent.p1() so any calls to Parent.p1() will actually call Child.p1() if you have an instance of class Child

Child.p1() calls MyBase.p2()

MyBase.p2() is actually Parent.p2()

 

The drawback happens when you have an instance of class Child and call procedures p1 and p2. Calling p1 produces the following implementation 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.

 

Applying 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

 

Have a nice coding!


                           Rate This Article:   

Author is Offline
  Author: Kay Yong Poy
       


Comments Posted
Label
Subject Author Status Date

Good!

Avlos Undjendjacky 30/11/2007

 

Post Comment

Related Articles
Fundamentals on .NET Framework
N-Tier in ASP.NET or other .NET apps
Software Development Outsourcing (Offshore ) to India
Make your web site ‘perfect and Search Engine Friendly for Google and Yahoo
Color combination of your Web site



Home | About Us | Site Map | Privacy Policy