Inheritance puzzle

G

Glenn Cory

Hi all,

I have hit a situation that has me stumped. I have two class
libraries called Base and Derived. They look like this:

' BASE
Public Class Class1
Public Overridable Sub DoSomething()
With New Class2()
.ShowMessage()
End With

MsgBox(Me.GetType.Assembly.FullName)
MsgBox(Me.GetType.Namespace)
End Sub
End Class
Public Class Class2
Public Overridable Sub ShowMessage()
MsgBox("I am Base.Class2")
End Sub
End Class

'DERIVED (this library references BASE)
Public Class Class1
Inherits Base.Class1

Public Overrides Sub DoSomething()
MyBase.DoSomething()
End Sub
End Class
Public Class Class2
Inherits Base.Class2

Public Overrides Sub ShowMessage()
MsgBox("I am Derived.Class2")
End Sub
End Class

So basically Derived.Class1 inherits from Base.Class1 and
Derived.Class2 inherits from Base.Class2. (Obviously this is a
simplified example and there would actually be more stuff in
DoSomething.)

My test program for this is a windows application that contains this:

Private Sub Form1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.Click
With New Base.Class1()
.DoSomething()
End With

With New Derived.Class1()
.DoSomething()
End With
End Sub

When I run this, the call to Base.Class1.DoSomething shows the message
"I am Base.Class2" as expected. My problem is that the call to
Derived.Class1.DoSomething shows the same thing instead of the "I am
Derived.Class2" that I was hoping for. So in both cases, it is using
Base.Class2. What I don't understand is why. The message boxes that
show the assembly and namespace both show "Derived" on the second
call. When it goes to create Class2, I guess I expected it to look in
the current assembly/namespace first (even though the actual running
code is in Base)

Am I missing something here?

For what I'm trying to accomplish, passing instance of the derived
classes into the base classes isn't an option. I did figure out a way
around this which works but seems really hokey (and probably isn't
very effecient) Instead of using

With New Class2

I have to use:

With Activator.CreateInstance(Me.GetType.Assembly.GetType(Me.GetType.Namespace
& ".Class2"))

Any thoughts on this will be greatly appreciated.

Thanks,
Glenn
 
N

NM

Hi,

You should overrides the method DoSomething in your DERIVED class class1 to
create DERIVED class class2 and call its method; like that :

'DERIVED (this library references BASE)
Public Class Class1
Inherits Base.Class1

Public Overrides Sub DoSomething()
With New Class2()
.ShowMessage()
End With

MsgBox(Me.GetType.Assembly.FullName)
MsgBox(Me.GetType.Namespace)
End Sub
End Class


Regards;
 

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