add section about classes

This commit is contained in:
Johannes Loher 2018-04-13 18:24:22 +02:00
parent bcb11b736b
commit 63444ed552

View file

@ -217,8 +217,8 @@ type qualifiers:
#### `immutable`
An object declared as `immutable` is enforced by the compiler to never change its
value.
An object declared as `immutable` is enforced by the compiler to never change
its value.
```D
immutable int a;
@ -735,3 +735,62 @@ if ("key1" in map) { // checking if a key is in an associative array
assert(map.length == 1); // associative arrays provide a .length property
map.remove("key1"); // remove a key from an associative array
```
### Classes
D's `class`es are very similar to Java's `class`es.
Any `class` type implicitely inherits from `Object`.
```D
class Foo { } // implicitely inherits from Object
class Bar : Foo { } // Bar inherits from Foo
```
`class`es are usually instantiated on the GC heap using `new`:
```D
auto bar = new Bar;
```
In contrast to `struct`s, `class`es are reference types:
```D
Bar bar = foo; // bar points to foo
```
#### Inheritance
If a member function of a base class if overwritten, the `override` keyword must
be used:
```D
class Bar: Foo {
override void functionFromFoo() {}
}
```
Classes can only inherit from a single class
#### Final and abstract member functions
* A function can be marked `final` in a base class to disallow overriding it.
* A function can be declared as `abstract` to force derived classes to override
it.
* A whole class can be declared as `abstract` to make sure that it isn't
instantiated.
* `super(…)` can be used to explicitly call the base constructor.
#### Checking for identity
The `==` operator compares the content of two class objects. Checking for
identity is done using the `is` operator. Coparing to `null` is only possible
with this operator:
```D
MyClass c;
if (c == null) // error
/* … */
if (c is null) // ok
/* … */
```