Object-Oriented Notes


Approach


Class Scope

 


Overloaded Constructors

A method's signature refers to the number, types and order of the arguments in the parameter list.

Methods of a class can be overloaded, but only by other methods of the same class.

To overload a method of a class, simply provide an additional method definition with the same name as the original method, but with a different parameter list.

The appropriate constructor is determined by checking the method signature specified in the constructor call with the signature specified in each method definition.

If a redefinition of a method has a different signature than the original method, it is method overloading . 

Constructors can be overloaded to initialize one, some, or all of an object's instance variables.

The next example overloads the New constructor method to provide a convenient variety of ways to initialize clsTime objects.


' No-argument constructor initializes each instance 
' variable to zero. Ensures that clsTime object starts in 
' a consistent state.
Public Sub New( )  
     setTime( 0, 0, 0 )
End Sub

' One-argument constructor: hour supplied, minute 
' and second default to 0.
Public Sub New( ByVal h As Integer ) 
     setTime( h, 0, 0 )
End Sub

' Two-argument  constructor: hour and minute supplied, second
' defaults to 0.
Public Sub New( ByVal h As Integer, ByVal m As Integer ) 
     setTime( h, m, 0 )
End Sub

' Three-argument constructor: hour, minute and second supplied.
Public Sub New( ByVal h As Integer, ByVal m As Integer, ByVal s As Integer ) 
     setTime( h, m, s )
End Sub

 


Dim t1 As clsTime = New clsTime ( )

Dim t2 As clsTime = New clsTime ( 2 )

Dim t3 As clsTime = New clsTime ( 21, 34 )

Dim t4 As clsTime = New clsTime ( 12, 25, 42 )

Dim t5 As clsTime = New clsTime ( 27, 74, 99 )

 

The appropriate constructor is determined by checking the number, types and order of the arguments specified in the constructor call with the number, types and order of the parameters specified in each method definition.

The matching constructor is called automatically.