Polymorphism, Abstract Classes and Method Overriding
What is Polymorphism?
Polymorphism means 'many forms'. You write code against a general type (like Shape) and each specific object (circle, rectangle) does the right thing in its own way.
Abstract Classes
An abstract class is an incomplete blueprint. You cannot create objects from it. It can force child classes to implement certain methods.
csharp
abstract class Shape
{
public string Color { get; set; } = "Black";
public abstract double Area(); // no body: children MUST implement
public virtual string Describe() => $"{GetType().Name} with area {Area():F2}";
}
class Circle(double radius) : Shape
{
public override double Area() => Math.PI * radius * radius;
}
class Rectangle(double width, double height) : Shape
{
public override double Area() => width * height;
public override string Describe() => $"Rectangle {width}x{height}, area {Area():F2}";
}
One List, Many Shapes
csharp
List<Shape> shapes =
[
new Circle(2),
new Rectangle(3, 4),
new Circle(1)
];
foreach (Shape s in shapes)
{
Console.WriteLine(s.Describe()); // each object runs ITS OWN version
}
double total = shapes.Sum(s => s.Area());
Why this matters: The loop does not care which kind of shape it holds. When you add a
Triangle class later, this code keeps working without any change.
virtual, override and new
| Keyword | Behavior |
|---|---|
virtual | Parent method that children may replace |
abstract | Parent method with no body that children must replace |
override | Child replaces the parent version |
new (hiding) | Child hides the parent version. Avoid it, it surprises people. |
Overriding ToString
csharp
class Point(int x, int y)
{
public override string ToString() => $"({x}, {y})";
}
Console.WriteLine(new Point(2, 3)); // (2, 3)
Type Checks and Casting
csharp
Shape shape = new Circle(3);
if (shape is Circle c)
Console.WriteLine("It is a circle");
Circle? maybe = shape as Circle; // null if the type does not match
Abstract Class vs Interface
| Abstract class | Interface | |
|---|---|---|
| Code inside | Can have fields and shared code | Mostly just a contract |
| Inheritance | A class inherits one | A class can implement many |
| Use when | Related classes share code | Unrelated classes share a capability |
Conclusion
Program against the general type, let each object provide its own behavior with override, and use abstract when children must supply a missing piece.
Quick Summary: abstract = must override, virtual = may override. Code against the parent type.

