Overriding versus Overloading - Overload a Constructor
(Page 3 of 4 )
In addition to overloading a method, we are also able to overload a constructor. In the same way we give the user different ways of calling a method, we can provide different ways to construct an object. In the Point class, we did just that when we created two constructors: a default constructor (no parameters) and a constructor that takes x and y values. Here is another example that illustrates the way we can overload a constructor:
namespace Overloading
{
class Program
{
static void Main( string [] args)
{
Fraction f1 = new Fraction ();
Console .WriteLine(f1.ToString());
Fraction f2 = new Fraction (3);
Console .WriteLine(f2.ToString());
Fraction f3 = new Fraction (2, 5);
Console .WriteLine(f3.ToString());
}
}
class Fraction
{
private int num;
private int denom;
//constructors
public Fraction()
{
num = denom = 1;
}
public Fraction( int n)
{
num = n;
denom = 1;
}
public Fraction( int n, int d)
{
num = n;
denom = d;
}
public override string ToString()
{
return string .Format( "Fraction {0}/{1} = {2}" ,
num, denom, ( double )num / denom);
}
}
}
In the Fraction class, we provided three different constructors:
public Fraction(): This is the default constructor. It allows the user to create the simplest fraction, 1 for the numerator and 1 for the denominator (1/1).
public Fraction( int n): This constructor is similar to the previous one, but it allows the user to set the numerator (denominator still 1).
public Fraction( int n, int d): This constructor gives the fullest flexibility because it allows the user to provide values for the numerator and the denominator.
Having these three constructors, now we can create different fractions based on our needs:
Fraction f1 = new Fraction ();
Fraction f2 = new Fraction (3);
Fraction f3 = new Fraction (2, 5);
Final note: The return type method cannot be used in the method signature to distinguish one method call from the other. So the following is not considered overloading; it is actually a compile time error:
public void Move( int delta_x, int delta_y) {...}
public int Move( int delta_x, int delta_y) {...}
The only difference between the two methods is that one returns a void, and the other returns an int.
Next: Overriding >>
More C# Articles
More By Ayad Boudiab