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?
If a base class has a default constructor, i.e., a constructor with no arguments, then that constructor is automatically called when a derived class is instantiated if the derived class has its own default constructor.
In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.
A derived class cannot have a constructor with default parameters. ____ 16. Default arguments can be used with an overloaded operator.
A constructor plays a vital role in initializing an object. An important note, while using constructors during inheritance, is that, as long as a base class constructor does not take any arguments, the derived class need not have a constructor function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With