Lesson 17 — Abstract Classes

Abstraction

Abstract classes define a template with shared concrete logic and abstract methods subclasses must implement. They enforce a contract while providing common functionality.

CSHARP — Abstract Shape
public abstract class Shape {
    public string Colour { get; }

    protected Shape(string colour) => Colour = colour;

    // Abstract — no body, subclasses MUST override:
    public abstract double Area();
    public abstract double Perimeter();

    // Concrete — shared by all shapes:
    public void Describe() =>
        Console.WriteLine(
            $"A {Colour} {GetType().Name}: " +
            $"Area={Area():F2} cm² | Perimeter={Perimeter():F2} cm");
}

public class Circle : Shape {
    private double _radius;
    public Circle(string colour, double radius) : base(colour) => _radius = radius;
    public override double Area()      => Math.PI * _radius * _radius;
    public override double Perimeter() => 2 * Math.PI * _radius;
}

public class Rectangle : Shape {
    private double _w, _h;
    public Rectangle(string colour, double w, double h) : base(colour) { _w=w; _h=h; }
    public override double Area()      => _w * _h;
    public override double Perimeter() => 2 * (_w + _h);
}
CSHARP — Usage
Shape[] shapes = {
    new Circle("gold", 5),
    new Rectangle("navy", 8, 3),
    new Circle("ivory", 2.5)
};

double total = 0;
foreach (var s in shapes) {
    s.Describe();
    total += s.Area();
}
Console.WriteLine($"Total area: {total:F2} cm²");

// Cannot instantiate:
// var s = new Shape("red"); // compile error: Cannot create instance of abstract class

Practice Task

Your Turn

Create abstract class Employee with Name, EmployeeId (readonly), HourlyRate (decimal), abstract CalculateMonthlyPay(). Implement FullTime (160hrs/month), PartTime (variable hours), Contract (fixed fee). Add shared PrintPaySlip() calling the abstract method. Store all in Employee[] and print pay slips.

Common Mistakes

  • Trying to instantiate an abstract class.
  • Forgetting override keyword on abstract method implementations.
  • Abstract class when an interface would be cleaner — use abstract class only when there is real shared state or behaviour.
  • Confusing abstract methods (no body, ; after signature) with virtual methods (have a body).

Professional Tip

The Template Method pattern: define the algorithm skeleton in the abstract class (with abstract steps), let subclasses fill in the steps. This is one of the most commonly used OOP patterns in enterprise .NET.

Mini Quiz

What must a concrete C# subclass do with all inherited abstract methods?