Inheritance

1 min read
On trails:CSOOPstep 3/6

Inheritance is a mechanism where a new class (the derived, or child, class) acquires the properties and methods of an existing class (the base, or parent, class). It establishes an “is-a” relationship, for example an ElectricCar is a Car, and it promotes code reuse.

In C#

An ElectricCar class can inherit from a Car class. The ElectricCar automatically gets common car functionality (like Steer() or Brake(), if defined in Car) and can add its own features, such as BatteryLevel and a Charge() method.

The : Vehicle and : Car on the class lines are the “is-a” relationship. Each class overrides DisplayInfo(), and calls the base version with base.DisplayInfo() before adding its own output.

C#
public class Vehicle{    public string Make { get; set; }    public string Model { get; set; }    public virtual void DisplayInfo()    {        Console.WriteLine($"Vehicle: {Make} {Model}");    }}public class Car : Vehicle{    public int NumberOfDoors { get; set; }    public override void DisplayInfo() // Overriding base class method    {        base.DisplayInfo();        Console.WriteLine($"Doors: {NumberOfDoors}");    }}public class ElectricCar : Car{    public int BatteryLevel { get; set; }    public void Charge() { Console.WriteLine("Charging battery..."); }    public override void DisplayInfo() // Further overriding    {        base.DisplayInfo(); // Calls Car's DisplayInfo        Console.WriteLine($"Battery: {BatteryLevel}%");    }}

Where it matters

Inheritance is a powerful tool for code reuse and for creating hierarchical classifications of objects. It forms the basis for polymorphismPolymorphismOne call, many behaviors, decided by the actual type at runtime.Opens in a new tab, which lets objects of derived classes be treated as objects of their base class.

Sources