Overloading Methods and Constructors
Often
you’ll want to have more than one function with the
same name. The most common example of this is to have more than one
constructor. In the examples shown so far, the constructor has taken
a single parameter: a DateTime object. It would be
convenient to be able to set new Time objects to
an arbitrary time by passing in year, month, date, hour, minute, and
second values. It would be even more convenient if some clients could
use one constructor, and other clients could use the other
constructor. Function overloading provides for exactly these
contingencies.
The signature of a method is defined by its name and its parameter list. Two methods differ in their signatures if they have different names or different parameter lists. Parameter lists can differ by having different numbers or types of parameters. For example, in the following code the first method differs from the second in the number of parameters, and the second differs from the third in the types of parameters:
void myMethod(int p1); void myMethod(int p1, int p2); void myMethod(int p1, string s1);
A class can have any number of methods, as long as each one’s signature differs from that of all the others.
Example 4-9 illustrates our Time
class with two constructors: one that takes a
DateTime object, and the other that takes six
integers.
Example 4-9. Overloading the constructor
public class Time { // private member variables private int Year; private int Month; private int Date; ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access