Home Vb.net Using child instance in a parent-typed variable
Reply: 1

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

pulse
1#
pulse Published in 2017-12-07 15:20:11Z

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.

A Friend
2#
A Friend Reply to 2017-12-07 15:57:40Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.312447 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO