Polymorphism is a concept in object-oriented programming that allows objects of different classes to be treated as objects of a common superclass. It enables you to invoke methods on objects without knowing their specific type, making your code more flexible and reusable.
Here's a simple explanation with an example:
Let's say we have a superclass called Shape
with a method Draw()
. We also have two subclasses: Circle
and Rectangle
, both of which override the Draw()
method to draw themselves in a different way.
Example
using System;
// Superclass
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}
// Subclass 1
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
// Subclass 2
class Rectangle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a rectangle");
}
}
class Program
{
static void Main(string[] args)
{
Shape[] shapes = new Shape[2];
shapes[0] = new Circle();
shapes[1] = new Rectangle();
// Polymorphic method call
foreach (Shape shape in shapes)
{
shape.Draw();
}
}
}
In this example:
Shape
with a virtual method Draw()
. This method is meant to be overridden by subclasses.Circle
and Rectangle
, both of which override the Draw()
method to draw themselves in their own way.Main
method, we create an array of Shape
objects and store instances of Circle
and Rectangle
in it. Since both Circle
and Rectangle
are subclasses of Shape
, they can be stored in an array of Shape
.Draw()
method on each object. Despite the objects being of different types (Circle
and Rectangle
), the correct Draw()
method is called for each object, demonstrating polymorphism.Polymorphism allows us to treat objects of different classes in a uniform manner, which promotes code flexibility and reusability.