.Net Object Inheritance
There is a nice little feature of OO (in .Net at least). When you create an object that is inherited from other objects, you can cast the object up and down the inheritance path to your hearts content, and the object happily retains its information from each of the levels, even though you might not be able to see that information at certain levels. The only proviso is that you can only convert as far down the chain as the original object. If you imagine an object as a sheet of paper, and a class as one of those ‘code cards’ you used to get as a kid (You know, the ones with the holes in specific locations that you could place over a sheet of paper to read the ‘hidden’ message. Although you are only able to see a subset of the information, all of the information is still contained on the page. You can change the code card to different types of card, but the underlying information remains.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | Module Module1
Sub Main()
Dim Guard As New GuardDog
Guard.Name = "Killer"
Guard.Location = "The Garden"
Guard.patrol()
Guard.Bark()
'Now we can convert the guard back into a basic pet object
Dim myPet As Pet = DirectCast(Guard, Pet)
Guard = Nothing
Console.WriteLine("Name: " & myPet.Name) 'Name: Killer
'We can still take this lower object, and convert it back up to a higher object.
Dim newGuard As GuardDog = DirectCast(myPet, GuardDog)
myPet = Nothing
'His properties are still the same as before
newGuard.patrol() 'Killer patrols The Garden, looking for intruders!
Console.ReadLine()
End Sub
End Module
Public Class Pet
Public Name As String
Public IsAlive As Boolean
End Class
Public Class Dog
Inherits Pet
Public Sub Bark()
Console.WriteLine(Me.Name & " Barks!")
End Sub
End Class
Public Class GuardDog
Inherits Dog
Public Location As String
Public Sub patrol()
Console.WriteLine(Me.Name & " Patrols " & Location & ", looking for intruders!")
End Sub
End Class |
This can be quite handy when passing objects back and forth between forms. If form a is expecting a type of pet, but you have a type of GuardDog, you can send it on fine. When the object is sent back to form b, you can convert it back up to the GuardDog type, in order to regain access to those object methods/properties.