Skip to content

Commit

Permalink
Merge pull request dlang-tour#348 from Imperatorn/patch-1
Browse files Browse the repository at this point in the history
Interfaces are implemented
  • Loading branch information
wilzbach authored Oct 23, 2020
2 parents 0cd6126 + 22197d0 commit ed14dea
Showing 1 changed file with 13 additions and 18 deletions.
31 changes: 13 additions & 18 deletions basics/interfaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ D allows defining `interface`s which are technically like
`class` types, but whose member functions must be implemented
by any class inheriting from the `interface`.

interface Animal {
interface IAnimal {
void makeNoise();
}

Expand All @@ -13,14 +13,13 @@ by `Dog` because it inherits from the `Animal` interface.
Essentially `makeNoise` behaves like an `abstract` member
function in a base class.

class Dog : Animal {
override void makeNoise() {
class Dog : IAnimal {
void makeNoise() {
...
}
}

auto dog = new Dog;
Animal animal = dog; // implicit cast to interface
IAnimal animal = new Dog(); // implicit cast to interface
animal.makeNoise();

Although a class may only directly inherit from *one* base class,
Expand All @@ -36,7 +35,7 @@ allowing `final` (i.e. non-overridable) functions in an `interface`.
This enforces specific behaviours customized by overriding
other abstract `interface` functions.

interface Animal {
interface IAnimal {
void makeNoise();
final doubleNoise() // NVI pattern
{
Expand All @@ -55,11 +54,7 @@ other abstract `interface` functions.
```d
import std.stdio : writeln;
interface Animal {
/*
Virtual function
which must be overridden!
*/
interface IAnimal {
void makeNoise();
/*
Expand All @@ -77,22 +72,22 @@ interface Animal {
}
}
class Dog: Animal {
override void makeNoise() {
class Dog: IAnimal {
void makeNoise() {
writeln("Woof!");
}
}
class Cat: Animal {
override void makeNoise() {
class Cat: IAnimal {
void makeNoise() {
writeln("Meeoauw!");
}
}
void main() {
Animal dog = new Dog;
Animal cat = new Cat;
Animal[] animals = [dog, cat];
IAnimal dog = new Dog;
IAnimal cat = new Cat;
IAnimal[] animals = [dog, cat];
foreach(animal; animals) {
animal.multipleNoise(5);
}
Expand Down

0 comments on commit ed14dea

Please sign in to comment.