pulse
pulse

Reputation: 1

Vb.net Using child instance in a parent-typed variable

I'm more familiar with how Java does polymorphism so I might be doing it wrong in vb

I'm trying use polymorphism and inheritance to have one instance that can take on multiple forms, the issue is the variable is instantiated as the parent type and initialized as a child class instance but I can't access the child properties.

below is an example what i'm trying to do:

sub main()
  Dim animal as Animal           'instantiated as parent type
  'some code later
  animal= New Dog()              'no problems here
  dim legs = animal.legs         'this works
  dim fur = animal.fur           'this is an error 
end sub

Public Class Animal
  Property legs as integer
End Class 

Public Class Dog
  inherits Animal
  Property fur as Boolean = True
End Class

It would be great if i could get this to work.

Upvotes: 0

Views: 460

Answers (1)

A Friend
A Friend

Reputation: 2750

This is actually declaring, not instantiating.

Dim animal as Animal

And if you know it is an animal, then create it as one like so:

Dim doggo As New Dog

The only time you should need to treat the Dog as an Animal is if you are performing something on it's Legs.

For example (in the Animal class):

Shared Sub AmputateLeg(patient As Animal)
    patient.Legs = patient.Legs - 1
End Sub

That you can call from Dog like so:

Dim doggo As New Dog()
doggo.Legs = 4
Animal.AmputateLeg(doggo)
Console.WriteLine(doggo.Legs) ' Shows 3.

As Plutonix commented, a base class should not know anything about the derived class, hence the IDE can't locate the Fur property when the Dog is treated as an Animal type

Perhaps you want something along the lines of an Interface instead

Public Interface IAnimal
    Property Fur As Boolean
    Property Legs As Integer
End Interface

Public Class Dog
    Implements IAnimal

    Public Property Fur As Boolean = True Implements IAnimal.Fur
    Public Property Legs As Integer = 4 Implements IAnimal.Legs
End Class

Public Class Duck
    Implements IAnimal

    Public Property Fur As Boolean = False Implements IAnimal.Fur
    Public Property Legs As Integer = 2 Implements IAnimal.Legs
End Class

Using an Interface this way means that you can always refer to Legs and Fur of any animal.

Upvotes: 1

Related Questions