Interfaces in D Programming Language

Interfaces are named collections of method signatures.

import std.stdio;
import std.math;

// Here's a basic interface for geometric shapes.
interface Geometry {
    double area();
    double perim();
}

// For our example we'll implement this interface on
// `Rect` and `Circle` types.
class Rect : Geometry {
    double width, height;

    this(double width, double height) {
        this.width = width;
        this.height = height;
    }

    // To implement an interface in D, we just need to
    // implement all the methods in the interface.
    double area() {
        return width * height;
    }

    double perim() {
        return 2*width + 2*height;
    }
}

class Circle : Geometry {
    double radius;

    this(double radius) {
        this.radius = radius;
    }

    // The implementation for `Circle`s.
    double area() {
        return PI * radius * radius;
    }

    double perim() {
        return 2 * PI * radius;
    }
}

// If a variable has an interface type, then we can call
// methods that are in the named interface. Here's a
// generic `measure` function taking advantage of this
// to work on any `Geometry`.
void measure(Geometry g) {
    writeln(g);
    writeln(g.area());
    writeln(g.perim());
}

void main() {
    auto r = new Rect(3, 4);
    auto c = new Circle(5);

    // The `Circle` and `Rect` classes both
    // implement the `Geometry` interface so we can use
    // instances of these classes as arguments to `measure`.
    measure(r);
    measure(c);
}

To run the program:

$ dmd -run interfaces.d
Rect
12
14
Circle
78.5398
31.4159

In D, interfaces are similar to those in other languages. They define a set of methods that a class must implement. Classes can implement multiple interfaces. The measure function demonstrates polymorphism, where it can work with any object that implements the Geometry interface.

To learn more about D’s interfaces, check out the D Programming Language documentation.