Lesson 7: Abstract Classes & Methods in C#
Abstract classes allow you to define a template for child classes while preventing direct instantiation. Use them to enforce contracts — child classes must implement certain behavior. This lesson covers abstract classes, abstract methods, and when to use them.
What Are Abstract Classes?
An abstract class is a class marked with the abstract keyword. You cannot instantiate it directly — only classes derived from it can be instantiated:
public abstract class Vehicle
{
public string Brand { get; set; }
public abstract void StartEngine(); // No implementation!
public void Stop()
{
Console.WriteLine("Vehicle stopped");
}
}
// ✗ Cannot create: new Vehicle()
// ✓ Must subclass instead
public class Car : Vehicle
{
public override void StartEngine()
{
Console.WriteLine("Starting car engine");
}
}
var car = new Car();
car.StartEngine(); // Output: Starting car engine
Abstract Methods
Abstract methods have no implementation — child classes must override them:
public abstract class Shape
{
public abstract double GetArea();
public virtual void Display()
{
Console.WriteLine($"Area: {GetArea()}");
}
}
public class Circle : Shape
{
public double Radius { get; set; }
public Circle(double radius) { Radius = radius; }
public override double GetArea()
{
return Math.PI * Radius * Radius;
}
}
var circle = new Circle(5);
circle.Display(); // Output: Area: 78.54...
Abstract Classes vs Interfaces
Use abstract classes for shared behavior. Use interfaces for contracts:
// Abstract class — shared implementation
public abstract class Animal
{
public void Sleep() { Console.WriteLine("Sleeping"); }
public abstract void Eat();
}
// Interface — contract
public interface IMovable
{
void Move();
}
// Usage
public class Dog : Animal, IMovable
{
public override void Eat() { Console.WriteLine("Eating"); }
public void Move() { Console.WriteLine("Running"); }
}
🧠 Quick Check — Lesson 7
Can you instantiate an abstract class directly?
Lesson Summary
Abstract classes cannot be instantiated directly — they serve as blueprints for derived classes.
Abstract methods have no implementation; child classes must override them with override.
Abstract classes can contain both abstract and concrete (implemented) methods.
Use abstract classes for shared behavior; use interfaces for contracts and multiple inheritance.
Abstract classes enforce that child classes implement certain behavior, preventing incomplete implementations.