Overloading and Overriding in Visual Basic.NET 2005 - A sample class with constructor overloading (Page 3 of 5 )
Overloading is not limited only to methods. We can even overload constructors, properties, and so forth. The following is a rewrite of the above class which includes both method and constructor overloading:
Public Class Sample3
Private _x As Double
Private _y As Double
Public Sub New()
End Sub
Public Sub New(ByVal a As Double)
_x = a
_y = a
'Me.SetValues(a)
End Sub
Public Sub New(ByVal a As Double, ByVal b As Double)
_x = a
_y = b
'Me.SetValues(a, b)
End Sub
Public Property X() As Double
Get
Return _x
End Get
Set(ByVal value As Double)
_x = value
End Set
End Property
Public Property Y() As Double
Get
Return _y
End Get
Set(ByVal value As Double)
_y = value
End Set
End Property
Public Sub SetValues(ByVal a As Double, ByVal b As Double)
_x = a
_y = b
End Sub
Public Sub SetValues(ByVal a As Double)
_x = a
_y = a
End Sub
Public Function GetProduct() As Double
Return _x * _y
End Function
End Class
As you can see from the comments in the above class, I am trying to call overloaded methods from overloaded constructors, which is possible.
The following is the code to test the constructors in the above class:
Dim obj As New Sample3(10, 20)
MessageBox.Show("Product = " & obj.GetProduct())
Dim obj2 As New Sample3(10)
MessageBox.Show("Product = " & obj.GetProduct())
Next: Method overriding in Visual Basic 2005 >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee