Casting and Overriding
Today I asked myself a question that I've asked myself many times. Today, however, I actually bothered to find out the answer.
Before you jump ahead, let me assure you that no, the question was not 'why do cows look so damn attractive?'.
Nor was it 'when is a duck?'.
It was 'If ClassA has a method Foo, and ClassB inherits ClassA, and ClassB over rides ClassA's foo, and then I create an instance of ClassB and cast it as ClassA, and then call Foo, which Foo runs?'
Stop and think about it. There's only two answers here - either ClassA's, or ClassB's. But there's a pretty strong case for both answers too. If I've cast to ClassA, then only ClassA methods should be called, right? But if ClassB has over ridden ClassA, and while we've cast to ClassA, it's still a ClassB behind the scenes that was instantiated. Oh the conundrum!
So which one is it? I decided it was time to find out - I was expecting the answer to be ClassA's, but I was hoping the answer would be ClassB's. If it was, then I could reduce the amount of code I had to write in a method I was writing by 75% (the method received an object of ClassA, but it was really either ClassB, C, D, or E, all of which inherit A. I needed to call the same method on all of them, but make sure that the over ridden method was called, not the just the base.
Well, here's the test code I whipped up. First I wrote classes A and B.
Public Class ClassA
Public Overridable Sub Foo()
Console.WriteLine("-This is A's Foo")
End Sub
End Class
Public Class ClassB
Inherits ClassA
Public Overrides Sub Foo()
Console.WriteLine("-This is B's Foo")
End Sub
End Class
Then I write something that calls it.
Module Module1
Sub Main()
Dim oA As New ClassA
Dim oB As New ClassB
Dim oC As ClassA = CType(oB, ClassA)
Console.WriteLine("Calling A's Foo")
oA.Foo()
Console.WriteLine("Calling B's Foo")
oB.Foo()
Console.WriteLine("Calling A's Foo on a B Object")
oC.Foo()
End Sub
End Module
And now <insert drumroll here> the results are:
Calling A's Foo
-This is A's Foo
Calling B's Foo
-This is B's Foo
Calling A's Foo on a B Object
-This is B's Foo
Well gosh! I was happy indeed. (I asked four other people at work what they predicted the results to be. Only one person got it right :)
Listening to: all my lovin - me first and the gimme gimmes - (1:54)