Challenge: Implement Inheritance Hierarchy

A coding challenge based on the concepts covered in this chapter.

We'll cover the following

Problem statement

Let’s modify RailwayVehicle. In addition to reporting the distance that it advances, let’s have it also make sounds. To keep the output short, let’s print the sounds per 100 kilometers:

class RailwayVehicle {
    void advance(size_t kilometers) {
        writefln("The vehicle is advancing %s kilometers", kilometers);

        foreach (i; 0 .. kilometers / 100) {
            writefln(" %s", makeSound()); 
        }
    }

    // ...
}

However, makeSound() cannot be defined by RailwayVehicle because vehicles may have different sounds:

  • “choo choo” for Locomotive
  • “clack clack” for RailwayCar

Because it must be overridden, makeSound() must be declared as abstract by the superclass:

class RailwayVehicle {
    //...

    abstract string makeSound();
}

Input

Implement makeSound() for the subclasses. Your code should work with the following main():

void main() {
    auto railwayCar1 = new PassengerCar; 
    railwayCar1.advance(100);

    auto railwayCar2 = new FreightCar; 
    railwayCar2.advance(200);

    auto locomotive = new Locomotive;
    locomotive.advance(300); 
}

Output

Make the program produce the following output:

The vehicle is advancing 100 kilometers
clack clack
The vehicle is advancing 200 kilometers
clack clack
clack clack
The vehicle is advancing 300 kilometers
choo choo
choo choo
choo choo

Note: There is no requirement that the sounds of PassengerCar and FreightCar be different. They can share the same implementation from RailwayCar.

Challenge

This problem is designed for you to practice, so try to solve it on your own first. If you get stuck, you can always refer to the explanation and solution provided in the next lesson. Good luck!

Get hands-on with 1400+ tech skills courses.