Inheritance problem - Base Class method being called when Derived Class method should be called.

J

Jeff Molby

This is blowing my mind. For some reason, A.Save() always calls A.Update().
Shouldn't it call B.Update() when the object is instantiated as a B? I've
been working with these classes for some time now, override methods without
any sort of problem, but for some reason this one just isn't working right.
Does it have something to do with the way I'm using the interface? Thanks
for any and all help!

Jeff



Interface Z
Sub Save()
End Interface


Class A
Implements Z

Public Sub Save() Iimplements Z.Save
Update()
End Sub

Protected Overridable Sub Update(Optional Byval ZeroRowsOK as boolean =
false)
'Does Stuff
End Sub
End Class

Class B
Inherits A

Protected Overrides Sub Update(Optional Byval ZeroRowsOK as boolean =
false)
'Does different stuff
End Sub
End Class


Class CallingClass

Public Shared Main()
Dim x As New B()

UtilityFunction(x)
End Sub

Sub UtilityFunction( i As Z)
i.Save()
End Sub
End Class
 
H

Herfried K. Wagner [MVP]

Jeff Molby said:
This is blowing my mind. For some reason, A.Save() always calls
A.Update(). Shouldn't it call B.Update() when the object is instantiated
as a B?
[...]
Interface Z
Sub Save()
End Interface

Class A
Implements Z

Public Sub Save() Iimplements Z.Save
Update()
End Sub

Protected Overridable Sub Update(Optional Byval ZeroRowsOK as boolean =
false)
'Does Stuff
End Sub
End Class

Class B
Inherits A

Protected Overrides Sub Update(Optional Byval ZeroRowsOK as boolean =
false)
'Does different stuff
End Sub
End Class


Class CallingClass

Public Shared Main()
Dim x As New B()

UtilityFunction(x)
End Sub

Sub UtilityFunction( i As Z)
i.Save()

The line above will call the 'Save' method defined in 'Z', because you are
passing your instance of 'B' in a variable/parameter of its base class.
Either change the data type of 'i' to 'B' or cast 'i' to 'B' inside
'UtilityFunction'.
 
J

Jeff Molby

I'm terribly sorry and humbled. I accidently put the overrides in a sister
class of B, so it's no wonder they weren't being called! :) That's what I
get for working on a Sunday.

SORRY!

P.S. If anyone has the capability, please destroy this proof of my idiocy.
 
H

Herfried K. Wagner [MVP]

Errata:

It seems that I mixed 'A', 'B', and 'Z'. However, the problem has already
been solved by the OP...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top