I was wondering if I could have the parent class instantiate an object of a child class, without going into an infinite recursion.
Consider this example:
Module Module1
Sub Main()
Dim _baseFruit As New Fruit
_baseFruit.Write()
Console.ReadKey()
End Sub
End Module
Public Class Fruit
Public Property Type As String
Public Property BaseType As String
Public Property FruitType As New Apple
Sub New()
Type = "Fruit"
BaseType = "N/A"
End Sub
Public Sub Write()
Console.WriteLine("Type: {0} BaseType: {1} FruitType: {2} ", Type, BaseType, FruitType.Type)
End Sub
End Class
Public Class Apple
Inherits Fruit
Public Sub New()
Me.Type = "Apple"
End Sub
End Class
As soon as an Apple is instantiated, it's entering the infinite recursion.
Is it incorrect to say this is impossible, that is to have a child referenced in the parent which is also the base ?
EDIT: From the answer below I have updated the code, lo and behold, it works.
Module Module1
Sub Main()
Dim _baseFruit As New Fruit
Dim _apple As New Apple
_baseFruit.Write(_apple)
Console.ReadKey()
End Sub
End Module
Public Class Fruit
Public Property Type As String
Public Property BaseType As String
Public Property FruitChildInstance As Apple
Sub New()
Type = "Fruit"
BaseType = "N/A"
End Sub
Public Sub Write(ByVal fruit As Apple)
FruitChildInstance = fruit
Console.WriteLine("Type: {0} BaseType: {1} FruitType: {2} ", Type, BaseType, FruitChildInstance.Type)
End Sub
End Class
Public Class Apple
Inherits Fruit
Public Sub New()
Me.Type = "Apple"
End Sub
End Class