Help with Inheritance

D

D Miller

This may be a basic question, but it sure has me stumpted..


I have two classes, Class1 and Class2. Class 2 inherits class one. Each
class has some varibles that need to be reset from time to time, so I have
created a method call "Clear" that does that. So my question is when using
"Clear" in an instance of class two, the clear method in Class one does not
get called, is there some way of excucting both "Clear" Methods in a single
call... See the code below for what I mean...

There must be a simple way of doing this, and I suspect I'm going to feel
pretty foolish when someone points it out, but it sure has me stumped at the
moment...

Thank you,
David


Public Class1
dim mQty as integer
dim mPrice as double


Public Sub Clear
mPrice = 0
mQty =0
end sub

Public Property Price as Double
Get
return mPrice
end get
Set(ByVal Value as Double)
mPrice = Value
end set
end property

Public Property Qty as Integer
Get
return mQty
end get
Set(ByVal Value as Integer)
mQty = Value
end set
end property
end class

Public Class2
inherits Class1
dim mInvoice as integer


Public Shadows Sub Clear
' HERE IS WHERE THE QUESTION IS. IS THERE SOME WAY OF HAVING THIS
METHOD RUN THE CLEAR METHOD OF CLASS1?
mInvoice = 0
end sub


Public Property Invoice as Integer
Get
return mInvoice
end get
Set(ByVal Value as Integer)
mInvoice = Value
end set
end property
end class

i
 
L

Lloyd Sheen

If I understand you have the two classes both with Clear methods. If you
call the Class2.Clear simply (depending on the language used) add a call to
the Clear in the parent class.

For VB.NET the syntax is MyBase.Clear()
For C# it is base.Clear();

Lloyd Sheen
 
E

EricJ

I think thats w Lloyd Sheen meanth

cl1
public sub clear()
'code
end sub

cl2 : cl1
public sub clear()
MyBase.Clear()
'code
end sub

hope it helps

eric
 
J

Jay B. Harlow [MVP - Outlook]

D Miller,
In addition to the other's comments I would recommend NOT using Shadows
here, I would recommend making Clear Overridable.

Making Clear Overridable will allow Class2.Clear to execute if you put a
Class2 object in a Class1 variable. If you left Class2.Clear Shadows, only
Class1.Clear would be called...
Public Class Class1
Public Overridable Sub Clear
mPrice = 0
mQty =0
end sub
end class
Public Class Class2
inherits Class1
Public Overrides Sub Clear MyBase.Clear()
mInvoice = 0
end sub
end class

Then you will be able to do:

Dim c As Class1() = New Class2()
c.Clear()

And Class2.Clear will be called, which will call Class1.Clear.

I tend to reserve Shadows for upgrade situations where the base method is
introduced that is not compatible with a derived method & a couple of other
specialized cases...

Hope this helps
Jay
 

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