We do it for runtime polymorphism. When we need to call a derived class method, but which derived class needs to be called depends on runtime based on user input. This is a very simple example:
static void Main(string[] args)
{
List<Shape> shapes = new List<Shape>();
shapes.Add(new Circle());
shapes.Add(new Square());
shapes.Add(new Rectangle());
foreach (Shape s in shapes)
s.Draw();
Console.Read();
}
public class Shape
{
public virtual void Draw() { }
}
public class Square : Shape
{
public override void Draw()
{
// Code to draw square
Console.WriteLine("Drawing a square");
}
}
public class Circle : Shape
{
public override void Draw()
{
// Code to draw circle
Console.WriteLine("Drawing a circle");
}
}
public class Rectangle : Shape
{
public override void Draw()
{
// Code to draw circle
Console.WriteLine("Drawing a rectangle");
}
}
*****Output:
Drawing a circle
Drawing a square
Drawing a rectangle*****
In practical scenario maybe the user determines at run-time which shape he wants to draw. So while implementing, you shd create an object of Shape class, and assign a Circle, Rectangle or Square to it depending on user selection (in a switch or if-else). And when you call Shape.Draw(), it will call the appropriate derived class method.