Sök…


Syntax

  • klass Foo {} // ärver från Object
  • klass Bar: Foo {} // Bar är också en Foo
  • Foo f = ny Foo (); // instansera nya föremål på högen

Anmärkningar

Se specifikationen , bläddra i ett bokkapitel om klasser , arv och spela interaktivt .

Arv

class Animal
{
    abstract int maxSize(); // must be implemented by sub-class
    final float maxSizeInMeters() // can't be overridden by base class
    {
        return maxSize() / 100.0;
    }
}

class Lion: Animal
{
    override int maxSize() { return 350; }
}

void main()
{
    import std.stdio : writeln;
    auto l = new Lion();
    assert(l.maxSizeInMeters() == 3.5);

    writeln(l.maxSizeInMeters()); // 3.5
}

instansiering

class Lion
{
    private double weight; // only accessible with-in class

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

    double weightInPounds() const @property // const guarantees no modifications
    // @property functions are treated as fields
    {
        return weight * 2.204;
    }
}

void main()
{
    import std.stdio : writeln;
    auto l = new Lion(100);
    assert(l.weightInPounds == 220.4);

    writeln(l.weightInPounds); // 220.4
}


Modified text is an extract of the original Stack Overflow Documentation
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow