Abstract classes
| Abstract skeletons | |
| Abstract methods | |
| Extend them | |
| Abstract vs interface |
Abstract skeletons
An abstract class holds shared code that is not meant to be used alone. It cannot be created with new, only extended by children.
abstract class Shape {
label(): string {
return "A shape";
}
}
Abstract methods
An abstract method declares a signature without a body. Every child must provide its own version of that method.
abstract class Shape {
abstract area(): number;
}
Extend them
Extend the abstract class to build a concrete child. Call super in the child constructor, then fill in each abstract method.
class Circle extends Shape {
constructor(public radius: number) {
super();
}
area(): number {
return 3.14 * this.radius * this.radius;
}
}
const circle = new Circle(2);
console.log(circle.area());
Abstract vs interface
Use an abstract class when children share real code, like helpers and default logic. Use an interface when only the shape matters and each class brings its own logic.
A class extends one parent but can implement many interfaces, so interfaces stay the tool for wide contracts.
interface HasArea {
area(): number;
}
class Square implements HasArea {
constructor(public side: number) {}
area(): number {
return this.side * this.side;
}
}
Next: static
Article author: Arthur Isaev