Labs ICT
โญ Pro Login

Inheritance

Inheritance lets you build new classes based on existing ones. The new class (derived class) gets everything the base class has, and you can add or override stuff. It's one of the pillars of OOP and saves you from rewriting code.

Base and Derived Classes

Think of a base class Vehicle. Every vehicle has a brand and a year. A Car is a vehicle, but it also has doors. Use the colon (:) to say "inherits from."


class Vehicle
{
    public string Brand { get; set; }
    public int Year { get; set; }

    public void Honk()
    {
        Console.WriteLine("Honk!");
    }
}

class Car : Vehicle
{
    public int Doors { get; set; }
}

Car myCar = new Car();
myCar.Brand = "Honda";
myCar.Year = 2020;
myCar.Doors = 4;
myCar.Honk();
    

Car didn't define Brand, Year, or Honk(), but it inherited them from Vehicle.

Try it Yourself โ†’

The base Keyword

Derived classes can call the base class's constructor with base. This ensures the base part of your object is properly initialized.


class Vehicle
{
    public string Brand { get; set; }

    public Vehicle(string brand)
    {
        Brand = brand;
    }
}

class Car : Vehicle
{
    public int Doors { get; set; }

    public Car(string brand, int doors) : base(brand)
    {
        Doors = doors;
    }
}

Car myCar = new Car("Mazda", 4);
Console.WriteLine($"{myCar.Brand} with {myCar.Doors} doors");
    

The : base(brand) calls the Vehicle constructor first, then the Car constructor runs.

Preventing Inheritance with sealed

Sometimes you want to stop other classes from inheriting from yours. Slap sealed on the class and that's it โ€” no more derivation.


sealed class Motorcycle : Vehicle
{
    public bool HasSidecar { get; set; }
}

class SportBike : Motorcycle { }
    

This won't compile. sealed classes are the end of the line.

Single Inheritance

C# only supports single inheritance โ€” one class can have only one direct base class. Want to combine multiple behaviors? You'll use interfaces for that, but we'll cover those in a later lesson.

๐Ÿงช Quick Quiz

Which symbol is used to inherit from a base class?