Overloading Methods and Constructors
Often you’ll want to have more than one method with the same name. The most common example of this is to have more than one constructor. Having more than one constructor allows you to create the object with different parameters. For example, if you were creating a Time object, you might have circumstances where you want to create the Time object by passing in the date, hours, minutes, and seconds. Other times, you might want to create a Time object by passing in an existing Time object. Still other times, you might want to pass in just a date, without hours and minutes. Overloading the constructor allows you to provide these various options.
Let’s return to the Time class you created in Example 5-3. It might be convenient to create a Time class object by passing in a DateTime object (provided by the Framework). On the other hand, it might also be convenient to pass in the hour, minute, second, and date. Some clients might prefer one or the other constructor; you can provide both and the client can decide which better fits the situation.
In order to overload your constructor, you must make sure that each constructor has a unique signature. The signature of a method is composed of its name and its parameter list. Two methods differ in their signatures if they have different names or different parameter lists.
Of course, constructors must all have the same name, as every constructor is named with the name of the class. Therefore, to overload ...
Get Programming Visual Basic .NET, Second Edition 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.