Explain the concept of polymorphism with examples.

12 minintermediateOOPpolymorphisminheritance

Quick Answer

Polymorphism allows objects to take multiple forms. Types include compile-time (method overloading) and runtime (method overriding, interface implementation). Same interface can have different implementations. Enables flexible, extensible code where you can work with base types but get specific behavior from derived types.

Detailed Answer

Polymorphism means "many forms" and allows objects to be treated as instances of their parent class while exhibiting behavior specific to their actual class. There are two types:

  1. Compile-time Polymorphism (Static) - Method Overloading, Operator Overloading
  2. Runtime Polymorphism (Dynamic) - Method Overriding

Example:

// Runtime Polymorphism Example
public abstract class Shape
{
    public abstract double CalculateArea();
}

public class Circle : Shape
{
    public double Radius { get; set; }
    
    public Circle(double radius)
    {
        Radius = radius;
    }
    
    public override double CalculateArea()
    {
        return Math.PI * Radius * Radius;
    }
}

public class Rectangle : Shape
{
    public double Width { get; set; }
    public double Height { get; set; }
    
    public Rectangle(double width, double height)
    {
        Width = width;
        Height = height;
    }
    
    public override double CalculateArea()
    {
        return Width * Height;
    }
}

public class Triangle : Shape
{
    public double Base { get; set; }
    public double Height { get; set; }
    
    public Triangle(double baseLength, double height)
    {
        Base = baseLength;
        Height = height;
    }
    
    public override double CalculateArea()
    {
        return 0.5 * Base * Height;
    }
}

// Usage - Single interface, multiple forms
List<Shape> shapes = new List<Shape>
{
    new Circle(5),
    new Rectangle(4, 6),
    new Triangle(3, 8)
};

foreach (Shape shape in shapes)
{
    Console.WriteLine($"Area: {shape.CalculateArea()}");
    // Each shape calculates area differently (polymorphic behavior)
}

Related Resources