Abstraction
Definition
Abstraction is the result of defining the common properties and methods observed in a set of different classes.
Abstract classes can not be instantiated.
TIP
Take into account that classes obtained through abstraction may not be abstract classes.
Example
In this example we are going to take a look at two different classes that have some common properties and methods. Through abstraction we'll to be able to define a parent class from which they will inherit.
Person class
export class Person {
private readonly name: string;
private readonly dateOfBirth: Date;
constructor(dateOfBirth: Date, name: string) {
this.dateOfBirth = dateOfBirth;
this.name = name;
}
public walk() {}
public run() {}
public sleep() {}
}
2
3
4
5
6
7
8
9
10
11
12
13
Cat class
export class Cat {
private readonly dateOfBirth: Date;
constructor(dateOfBirth: Date) {
this.dateOfBirth = dateOfBirth;
}
public crawl() {}
public run() {}
public sleep() {}
}
2
3
4
5
6
7
8
9
10
11
It is clear that those two classes have dateOfBirth
, run
and sleep
in common. Let's abstract those common properties and methods into a new class.
Animal class
abstract class Animal {
protected readonly dateOfBirth: Date;
constructor(dateOfBirth: Date) {
this.dateOfBirth = dateOfBirth;
}
public abstract run(): void;
public sleep() {
// Implement the common logic for sleep
}
}
2
3
4
5
6
7
8
9
10
11
12
13
As we can see we have defined properties and methods that can be found in both classes. If you pay close attention to the run
method you'll see it is abstract
, this means that classes that inherit from Animal
will have to implement that logic.
It makes complete sense because the details of how a Person
runs are very different from how a Cat
runs (just picture a person running on their two feet and a cat on their four paws).
We should always review the classes that triggered that abstraction to make sure they now inherit the new class.
Person class
export class Person extends Animal {
private name: string;
constructor(dateOfBirth: Date, name: string) {
super(dateOfBirth);
this.name = name;
}
public walk() {
// Implement walk
}
public run() {
// Implement how a person runs
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Cat class
export class Cat extends Animal {
constructor(dateOfBirth: Date) {
super(dateOfBirth);
}
public crawl() {
// Implement crawl
}
public run() {
// Implement how a Cat runs
}
}
2
3
4
5
6
7
8
9
10
11
12
13
Benefits
By using abstraction we are able to remove duplicated code while also creating or expanding our classification hierarchy.