Polymorphic behaviors
Use interface-based polymorphism: process mixed shapes uniformly, add new shapes without changing callers, and compose small behaviors.
Polymorphism overview
Goal: Use polymorphism to keep callers simple.
- Work with IShape everywhere
- Mix many shapes in one list
- Add new shapes without changing code
- Compose tiny behaviors (formatting, filtering)
One API for all shapes
Accept the IShape interface in helpers. Runtime dispatch picks the right implementation.
using System;
public interface IShape
{
double Area();
double Perimeter();
}
public sealed class Rectangle : IShape
{
private readonly double _w, _h;
public Rectangle(double w, double h) { _w = w; _h = h; }
public double Area() { return _w * _h; }
public double Perimeter() { return 2 * (_w + _h); }
}
public sealed class Circle : IShape
{
private readonly double _r;
public Circle(double r) { _r = r; }
public double Area() { return 3.14159 * _r * _r; }
public double Perimeter() { return 2 * 3.14159 * _r; }
}
public class Program
{
// One function works for any IShape (dynamic dispatch on overrides)
static void PrintSummary(IShape s)
{
Console.WriteLine("A=" + s.Area() + " P=" + s.Perimeter());
}
public static void Main(string[] args)
{
PrintSummary(new Rectangle(3, 4));
PrintSummary(new Circle(2));
}
}
All lessons in this course
- Design (interfaces + inheritance)
- Implementation & tests
- Polymorphic behaviors