Inheritance, abstract classes and interfaces in C#

Lesson 8 of 15 · C#

With inheritance a new class takes over the data and methods of an existing class and adds its own. Polymorphism makes it possible to process objects of different classes together, while each one behaves "in its own way". An interface is a contract: a list of methods a class promises to have.

Before you start: required prior knowledge – classes and objects.
How to learn: type in and run every example, and solve the tasks at the end on your own first; open the hint and the solution only after that. All programs are C# console applications (.NET 8 or later, without "top-level statements"); every one has been tested and gives the output shown.

Inheritance: base, virtual and override

using System;

class Person
{
    public string Name { get; }
    public int Age { get; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    // virtual: derived classes are allowed to change this method
    public virtual string Description() => $"{Name}, {Age} years old";
}

class Student : Person                     // Student inherits the class Person
{
    public int Grade { get; }

    public Student(string name, int age, int grade) : base(name, age)   // the base class constructor
    {
        Grade = grade;
    }

    public override string Description() => base.Description() + $", a student in grade {Grade}";
}

class Teacher : Person
{
    public string Subject { get; }

    public Teacher(string name, int age, string subject) : base(name, age)
    {
        Subject = subject;
    }

    public override string Description() => base.Description() + $", teaches {Subject}";
}

class Program
{
    static void Main()
    {
        Person[] people =
        {
            new Student("Anna", 13, 7),
            new Teacher("Peter", 41, "computer science"),
            new Person("Mila", 30)
        };
        foreach (Person p in people)
            Console.WriteLine(p.Description());    // Description() of the object's actual class is called
    }
}

A derived class is written as class Student : Person. It has all the public members of the class Person plus its own additional ones. The base class constructor is called with : base(…), and base.Description() calls the original method.

The array of type Person[] contains both a student and a teacher. For each object the Description() of its actual class is called – this is polymorphism. For this to work, the base method must be virtual, and the new version must be marked with override.

Abstract classes

An abstract class (abstract) serves only as the basis for other classes – no objects can be created from it. An abstract method has no body, and every derived class must write it.

using System;

abstract class Shape
{
    public abstract double Area();              // no body
    public abstract double Perimeter();

    public override string ToString() => $"{GetType().Name}: A = {Area():F2}, P = {Perimeter():F2}";
}

class Circle : Shape
{
    private readonly double r;
    public Circle(double r) { this.r = r; }
    public override double Area() => Math.PI * r * r;
    public override double Perimeter() => 2 * Math.PI * r;
}

class Rectangle : Shape
{
    private readonly double a, b;
    public Rectangle(double a, double b) { this.a = a; this.b = b; }
    public override double Area() => a * b;
    public override double Perimeter() => 2 * (a + b);
}

class Program
{
    static void Main()
    {
        Shape[] shapes = { new Circle(1), new Rectangle(3, 4), new Circle(2.5) };
        double total = 0;
        foreach (var s in shapes)
        {
            Console.WriteLine(s);
            total += s.Area();
        }
        Console.WriteLine($"Total area: {total:F2}");
        // var x = new Shape();                 // error: an abstract class has no objects
    }
}

GetType().Name returns the name of the object's actual class, so a single ToString method in the base class works for all shapes.

Interfaces

An interface (interface, whose name by convention starts with the letter I) contains only the signatures of methods and properties. A class can inherit only one class, but it can implement several interfaces. The is operator checks whether an object implements an interface.

using System;

interface ISound
{
    string Voice();
}

interface IMovement
{
    int Speed { get; }
}

class Dog : ISound, IMovement              // two interfaces
{
    public string Voice() => "Woof woof";
    public int Speed => 40;
}

class Cat : ISound
{
    public string Voice() => "Meow";
}

class Car : IMovement
{
    public int Speed => 130;
}

class Program
{
    static void Main()
    {
        ISound[] sounds = { new Dog(), new Cat() };
        foreach (var s in sounds)
            Console.WriteLine(s.Voice());

        object[] things = { new Dog(), new Cat(), new Car() };
        foreach (var t in things)
        {
            if (t is IMovement m)                 // can the object move?
                Console.WriteLine($"{t.GetType().Name} goes {m.Speed} km/h");
            else
                Console.WriteLine($"{t.GetType().Name} does not move");
        }
    }
}

The IComparable interface: sorting your own objects

Array.Sort and List.Sort can sort objects of a class that implements IComparable<T>. The CompareTo method returns a negative number if this object comes before the other one, zero if they are equal, and a positive number if it comes after.

using System;

class Competitor : IComparable<Competitor>
{
    public string Name { get; }
    public int Points { get; }

    public Competitor(string name, int points)
    {
        Name = name;
        Points = points;
    }

    // more points come first; with the same number of points – alphabetically by name
    public int CompareTo(Competitor other)
    {
        if (Points != other.Points)
            return other.Points.CompareTo(Points);
        return string.Compare(Name, other.Name, StringComparison.Ordinal);
    }
}

class Program
{
    static void Main()
    {
        Competitor[] c =
        {
            new Competitor("Luke", 85), new Competitor("Anna", 92),
            new Competitor("Ivy", 85), new Competitor("Nick", 70)
        };
        Array.Sort(c);
        for (int i = 0; i < c.Length; i++)
            Console.WriteLine($"{i + 1}. {c[i].Name} ({c[i].Points})");
    }
}

Sorting can also be specified without an interface – with a lambda expression or a LINQ query, as shown in the lesson LINQ queries and lambda expressions.

Practice tasks

Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.

TASK 01Difficulty: medium

Employee salaries

Write an abstract class Employee (a name and an abstract method Salary()) and two derived classes: Worker (salary = hourly rate · number of hours) and Manager (salary = base salary · (1 + bonus/100)). Input: the number of employees n, then n lines of the form W name hourlyRate hours or M name baseSalary bonus (whole numbers). Print the salary of each employee and the total amount, with two decimal places.

Example

Input

3
W Mark 800 160
M Joanna 150000 20
W Ivan 950 120

Output

Mark: 128000.00
Joanna: 180000.00
Ivan: 114000.00
Total: 422000.00
TASK 02Difficulty: medium

The largest area

Write an interface IShape with a method double Area() and a property string Name, and the classes Circle, Rectangle and Triangle (area by Heron's formula). Input: the number of shapes, then lines C r, R a b or T a b c (whole numbers). Print the name of the shape with the largest area and its area with two decimal places.

Example 1

Input

3
C 2
R 3 5
T 3 4 5

Output

Rectangle 15.00

Example 2

Input

2
T 5 5 6
C 3

Output

Circle 28.27
Common mistakes and tips
  • A base method that a derived class changes must be virtual (or abstract), and the new version override.
  • A class inherits at most one class, but it can implement several interfaces: class Dog : Animal, ISound, IMovement.
  • No objects can be created from an abstract class or an interface, but variables of that type can exist.
  • A protected member is visible to the class and its derived classes, but not to the rest of the program.

Check your knowledge

Open the quiz

Inheritance and interfaces in C#

1. How do you write that the class Student inherits the class Person?




2. What must a base class method have so that a derived class can change it with override?




3. How many interfaces can a class implement?




4. Which is true for an abstract class?