Example

Let’s further learn about inheritance concepts using examples.

We'll cover the following...

Railway car example

Let’s consider a class hierarchy that represents railway vehicles:

The functions that RailwayCar will declare as abstract are indicated by question marks.

Since our goal is only to present a class hierarchy and point out some of its design decisions, we will not fully implement these classes. Instead of doing actual work, they will simply print messages.

The most general class of the hierarchy above is RailwayVehicle. In this program, it will only know how to move itself:

Press + to interact
import std.stdio;
class RailwayVehicle {
void advance(size_t kilometers) {
writefln("The vehicle is advancing %s kilometers", kilometers);
}
}
void main() {
}

A class that inherits from RailwayVehicle is Locomotive, which does not have any special members yet:

Press + to interact
import std.stdio;
class RailwayVehicle {
void advance(size_t kilometers) {
writefln("The vehicle is advancing %s kilometers", kilometers);
}
}
class Locomotive : RailwayVehicle {
}
void main() {
}

...