Overriding versus Overloading - Method Overloading Example
(Page 2 of 4 )
Here is a full example that illustrates method overloading:
namespace OverloadingMethods
{
class Program
{
static void Main( string [] args)
{
Point p1 = new Point ();
Console .WriteLine( "p1 -> {0}" , p1);
p1.Move();
Console .WriteLine( "p1 -> {0}" , p1);
p1.Move(2);
Console .WriteLine( "p1 -> {0}" , p1);
p1.Move(4, 7);
Console .WriteLine( "p1 -> {0}" , p1);
Point p2 = new Point (2, 5);
Console .WriteLine( "p2 -> {0}" , p2);
p2.Move(10, 9);
Console .WriteLine( "p2 -> {0}" , p2);
p2.Move();
Console .WriteLine( "p2 -> {0}" , p2);
}
}
class Point
{
private int x;
private int y;
Random rand = new Random ();
public Point()
{
x = y = 0;
}
public Point( int x_value, int y_value)
{
x = x_value;
y = y_value;
}
//Move x with a random number between 1 and 100 (inclusive)
//Move y with a random number between 1 and 50 (inclusive)
public void Move()
{
x += rand.Next(1, 101);
y += rand.Next(1, 51);
}
//move x and y by the same number (delta)
public void Move( int delta)
{
x += delta;
y += delta;
}
//move x and y by the specified values
public void Move( int delta_x, int delta_y)
{
x += delta_x;
y += delta_y;
}
public override string ToString()
{
return string .Format( "[{0},{1}]" , x, y);
}
}
}
Notice that the Point class is flexible in the way a point can be moved. By overloading the Move() method, we are able to move a point via different x and y values, via the same value (delta), or via random x and y values. This way, our class gives its user different ways of moving a point using the same friendly Move() method.
Next: Overload a Constructor >>
More C# Articles
More By Ayad Boudiab