Casting objects - Polymorphism

BlitzMax Forums/BlitzMax Beginners Area/Casting objects - Polymorphism

all your aliens have health right? that means it should be in your base ONLY.

My TAlien's baseclass was a class TUnit. And a TUnit has no health.
So I defined health in every class and used the creator new().
That caused trouble. The way I did it:
SuperStrict
Type TUnit
       ' I am just a graphicobject, no health for me
End Type

Type TAlien Extends TUnit
	Field health:Int = 1
	Field name:String = "Alien"
	'
	Method PrintHealth() 
		Print "Health in "+name+" = "+health
	End Method
End Type

Type TAlienSmall Extends TALien
	Field health:Int = 99
	Method New()
		health = 99				' health will never be 99 !!
		name = "AlienSmall"
	End Method
End Type

Type TAlienBig Extends TAlien
    ' no health defined here, correct value returned
     Method New()
		health = 3
		name = "AlienBig"
       End Method
End Type

' Main
Local alienlist:TList = New TList
Local as:TalienSmall = New TAlienSmall
Local ab:TAlienBig = New TAlienBig

alienlist.AddLast(as)
alienlist.AddLast(ab)

For Local alien:TAlien = EachIn alienlist
	'
	alien.PrintHealth
	Print alien.health
Next

With health defined only in TAlien my code works fine.

... to access those fields you need to directly cast to TAlienSmall or TAlienBig. but that's not what you want here....

Can I have an example? I'm sure I will need it in the future.

Also, encapsulating your lists, especially your base list (but I say all of them) will gain you many advantages.
I can show you that for this example if you would like.

Would be appreciated.