oscilatingcretin
oscilatingcretin

Reputation: 10959

Can I have my derived class automatically use the base constructor?

I have an abstract class that has two constructors. When another class inherits this class, it appears that I have to declare contructors with identical signatures as the ones in the base class. This seems a bit redundant to me. Is there a way to have Sub New(Parameter as MyClass) in my base class and have this become the default constructor signature unless the derived class includes it in its definition?

Edit for clarity: I was hoping it was implied that I do not want to have to create a constructor in the derived class that calls the base class. I would like to be able to do this:

Mustinherit Class MyBase

  Sub New(MyParam As String)

  End Sub

End Class

Class MyDerived
  Inherits MyBase

End Class

Notice now the derived class doesn't call the base?

Upvotes: 8

Views: 33805

Answers (2)

PhonicUK
PhonicUK

Reputation: 13864

In VB.Net you use:

MyBase.New(args)

Inside your constructors method body, no extra verbiage is used on the constructors/method signature.

Upvotes: -5

dario_ramos
dario_ramos

Reputation: 7309

Your assumption is wrong; your derived classes' constructors can have any signature, as long as they call one of their base class's constructor properly using MyBase.New. Here's a full example:

Imports System

Public Class MainClass

    Shared Sub Main()
         Dim w As New Window(5, 10)
         w.DrawWindow(  )

         Dim lb As New ListBox(20, 30, "Hello world")
         lb.DrawWindow(  )

    End Sub
End Class

 Public Class Window
     Public Sub New(ByVal top As Integer, ByVal left As Integer)
         Me.top = top
         Me.left = left
     End Sub 'New

     Public Sub DrawWindow(  )
         Console.WriteLine("Drawing Window at {0}, {1}", top, left)
     End Sub

     Private top As Integer
     Private left As Integer

 End Class

 Public Class ListBox
     Inherits Window

     Public Sub New(ByVal top As Integer, ByVal left As Integer, ByVal theContents As String)
         MyBase.New(top, left) ' 
         mListBoxContents = theContents
     End Sub 

     Public Shadows Sub DrawWindow(  )
         MyBase.DrawWindow(  ) 
         Console.WriteLine("Writing string to the listbox: {0}", mListBoxContents)
     End Sub 

     Private mListBoxContents As String 

 End Class

EDIT: You are not forced to keep or extend the base class constructor's signature at all. This is valid, for example:

Public Class ListBox
     Inherits Window

     Public Sub New(ByVal theContents As String)
         MyBase.New(20, 30) ' 
         mListBoxContents = theContents
     End Sub 

     'More code

 End Class

Upvotes: 34

Related Questions