Skip to content

Commit f775b96

Browse files
authored
Update classes.md Abstract section.
Add the example code in the Abstract section to improve the explanation and help to understand how abstract classes work.
1 parent 9c429a9 commit f775b96

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

docs/classes.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,37 @@ As always these modifiers work for both member properties and member functions.
120120
`abstract` can be thought of as an access modifier. We present it separately because opposed to the previously mentioned modifiers it can be on a `class` as well as any member of the class. Having an `abstract` modifier primarily means that such functionality *cannot be directly invoked* and a child class must provide the functionality.
121121

122122
* `abstract` **classes** cannot be directly instantiated. Instead the user must create some `class` that inherits from the `abstract class`.
123+
124+
```ts
125+
abstract class FooCommand {}
126+
127+
class BarCommand extends FooCommand {}
128+
129+
const fooCommand: FooCommand = new FooCommand(); // Cannot create an instance of an abstract class.
130+
131+
const barCommand = new BarCommand(); // You can create an instance of a class that inherits from an abstract class.
132+
```
133+
123134
* `abstract` **members** cannot be directly accessed and a child class must provide the functionality.
124135

136+
```ts
137+
abstract class FooCommand {
138+
abstract execute(): string;
139+
}
140+
141+
class BarErrorCommand extends FooCommand {} // 'BarErrorCommand' needs implement abstract member 'execute'.
142+
143+
class BarCommand extends FooCommand {
144+
execute() {
145+
return `Command Bar executed`;
146+
}
147+
}
148+
149+
const barCommand = new BarCommand();
150+
151+
barCommand.execute(); // Command Bar executed
152+
```
153+
125154
### Constructor is optional
126155

127156
The class does not need to have a constructor. e.g. the following is perfectly fine.

0 commit comments

Comments
 (0)