Языки

PHP
Функции  Добавить  Пользователи  Регистрация  Вход   Ресурс  Таблица ASCII  Помощь

VB.Net


1 MyClass - Implementing Polymorphism in VB.Net

2 Code

Code



(Page 2 of 2 )

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

If MyClass is not implemented above in the base class, you will get a stack overflow error. So why does the stack overflow occur?

  • 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()

Now if you are still with me, 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

I hope this will help VB.Net developers along the way to develop software the object-oriented way.


1 2
Citizen Science

eggs in a nest Volunteers help scientists understand birds and changing habitats

Full story at http://www.nsf.gov/news/special_reports/science_nation/citizenscience.jsp?WT.mc_id=USNSF_51


This is an NSF News item.

English
version


Статьи
Articles


Книги
Library


Скачать
Downloads

 © Internet, books, teachers and Rudevich Alexander brains.