Inheritance & Polymorphism
Lesson 8 • Intermediate Track
Extend base classes and override methods — the OOP pillars that make code extensible and reusable.
What You'll Learn
- • Create class hierarchies with the
:inheritance syntax - • Pass data to parent constructors with
: base() - • Override methods using
virtualandoverride - • Apply polymorphism — same type, different behaviour at runtime
- • Build abstract classes that define contracts for derived classes
- • Use pattern matching with
isfor safe type checking
Real-World Analogy
Inheritance is like biology — a "Dog" is a specialised type of "Animal" that inherits general traits but adds its own. Polymorphism is like a universal remote's "play" button — pressing it does different things depending on whether the TV, DVD player, or music app receives the signal.
Running C# Locally: Install the .NET SDK or use dotnetfiddle.net.
📋 Inheritance Keywords Reference
| Keyword | Where | What It Does |
|---|---|---|
| : | Class declaration | class Dog : Animal |
| base() | Constructor | Calls parent constructor |
| virtual | Base method | Marks method as overridable |
| override | Derived method | Replaces base implementation |
| abstract | Class/method | Must be inherited/implemented |
| sealed | Class/method | Prevents further inheritance |
| is | Type check | if (animal is Dog d) |
Basic Inheritance & Constructor Chaining
A derived class inherits everything from its base class. Use : base() in the constructor to pass data up to the parent. The base constructor runs first, then the derived constructor.
Basic Inheritance — Vehicles
Create Car and Motorcycle classes that inherit from Vehicle.
using System;
// Base class (parent)
class Vehicle
{
public string Brand { get; set; }
public int Year { get; set; }
public Vehicle(string brand, int year)
{
Brand = brand;
Year = year;
}
public void Start()
{
Console.WriteLine($"{Brand} ({Year}) — engine started! 🚗");
}
}
// Derived class (child) — inherits from Vehicle
class Car : Vehicle
{
public int Doors { get; set; }
// Constructor calls base constructor with : base(...)
...Method Overriding with virtual & override
Mark base methods as virtual to allow overriding. Use override in the derived class. You can call the original with base.MethodName() to extend rather than replace behaviour.
Method Overriding — Shapes
Override GetArea() in Circle and Rectangle to calculate areas.
using System;
class Shape
{
public string Name { get; set; }
public Shape(string name) { Name = name; }
// virtual = "derived classes CAN override this"
public virtual double GetArea()
{
return 0;
}
public virtual string Describe()
{
return $"{Name}: area = {GetArea():F2}";
}
}
class Circle : Shape
{
public double Radius { get; set; }
public Circle(double radius) : base("Circle")
{
Radius = radius;
}
// overri
...Polymorphism — Same Type, Different Behaviour
Store different derived objects in a base-type array. When you call a virtual method, C# automatically calls the correct override based on the actual object type at runtime.
Polymorphism — Animal Roll Call
Call Speak() on different animals through a shared base type.
using System;
class Animal
{
public string Name { get; set; }
public Animal(string name) { Name = name; }
public virtual void Speak()
{
Console.WriteLine($"{Name} makes a sound.");
}
}
class Dog : Animal
{
public Dog(string name) : base(name) { }
public override void Speak() => Console.WriteLine($"{Name}: Woof! 🐕");
}
class Cat : Animal
{
public Cat(string name) : base(name) { }
public override void Speak() => Console.WriteLine($"{Name}: Meow! 🐈
...Common Mistakes
- • Forgetting
virtual: Without it on the base method, you can't useoverride. - • Using
newinstead ofoverride:newhides the base method and breaks polymorphism. - • Not calling
: base(): If the parent has no parameterless constructor, you must pass required arguments. - • Deep inheritance chains: Keep hierarchies to 2-3 levels max. Prefer composition for code reuse.
Abstract Classes — Enforcing Contracts
An abstract class cannot be instantiated — it exists only to be inherited. Abstract methods have no body and must be implemented by every derived class.
Abstract Classes — Employee Payroll
Define an abstract Employee with different pay calculations per type.
using System;
// abstract = cannot be instantiated, only inherited
abstract class Employee
{
public string Name { get; set; }
public double BaseSalary { get; set; }
public Employee(string name, double baseSalary)
{
Name = name;
BaseSalary = baseSalary;
}
// Abstract method — derived classes MUST implement
public abstract double CalculatePay();
// Regular method — inherited as-is
public void PrintPayslip()
{
Console.WriteLine($"{
...Pro Tips
- 💡 Favour composition over inheritance — don't create 5+ level hierarchies.
- 💡 Use
sealedto prevent unintended inheritance of stable classes. - 💡 Pattern matching with
is:if (animal is Dog dog)checks and casts in one step. - 💡 Abstract classes can have fields and implemented methods — interfaces define pure contracts.
Lesson Complete! 🎉
You've mastered inheritance and polymorphism. Next up: Collections — List, Dictionary, Stack, Queue, and more.
Sign up for free to track which lessons you've completed and get learning reminders.