add section about classes
This commit is contained in:
parent
bcb11b736b
commit
63444ed552
1 changed files with 61 additions and 2 deletions
|
@ -217,8 +217,8 @@ type qualifiers:
|
||||||
|
|
||||||
#### `immutable`
|
#### `immutable`
|
||||||
|
|
||||||
An object declared as `immutable` is enforced by the compiler to never change its
|
An object declared as `immutable` is enforced by the compiler to never change
|
||||||
value.
|
its value.
|
||||||
|
|
||||||
```D
|
```D
|
||||||
immutable int a;
|
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
|
assert(map.length == 1); // associative arrays provide a .length property
|
||||||
map.remove("key1"); // remove a key from an associative array
|
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
|
||||||
|
/* … */
|
||||||
|
```
|
||||||
|
|
Loading…
Reference in a new issue