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
This could be called an “infinite type”. It doesn’t have to be a problem if you allow the member variable to be left empty.
Without looking at the actual meaning of this code, you could say this:
Dictating that the
FruitTypemember has to be anAppleinstance results in an infinite amount of objects nesting. Leaving it uninitialized (Dim FruitType as Fruit) would cause no problem at all.Now when you do take the semantic into account:
You’re mixing the “Type” concept with the “Instance” concept: a
Fruitinstance has-a type (e.g. the classApple), but it’s quite strange to let it have-a Fruit member, too.If you would have modeled this as a class
FruitType, where aFruithas a member dimensionedFruitType, the infinite recursion wouldn’t have happened.