4.5. Overloading

Look at Payment.Bill (in Example 4-1) for minute. In its current state, it does not take any parameters. Whatever amount was authorized is the amount that will be billed. But the online shopping world is strange. It is possible that when this payment is billed, not all of the items that were originally purchased will be in stock. Should the order be canceled? Of course not. You should notify the customer, bill for what you have, and ship the order. The problem is that the customer can't be billed for anything that hasn't shipped. And as it stands now, there is no way to bill a partially available order by using the Payment class.

You need an additional billing method that allows an amount to be specified. It is possible to define two or more methods that have the same name, but a different number of parameters. Then the functionality can be implemented for each case. Example 4-5 shows two versions of Bill: one that accepts an amount and one that does not. This process is called overloading.

Example 4-5. Overloading a method
Imports System
   
Public MustInherit Class Payment
  
  'Other class methods are here 
  
  Public Function Bill( ) As Boolean
    'Bill authorized amount
  End Function
   
  Public Function Bill(ByVal amount As Double) As Boolean
    If amount > Me.amount Then
      amount = Me.amount
    End If
    'Bill specified amount here
  End Function
  
End Class

If a method is overloaded in a derived class, then it needs to be explicitly expressed by using the Overloads keyword:

Public Class ...

Get Object-Oriented Programming with Visual Basic .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.