capypad
0 day streak
typescript / intermediate
Snippet

Abstract Classes for Shared Logic

Abstract classes cannot be instantiated directly. They serve as templates, allowing you to define shared methods while forcing subclasses to implement specific 'abstract' logic.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
abstract class Shape {
constructor(public color: string) {}
abstract getArea(): number;
 
printColor() {
console.log(`Color: ${this.color}`);
}
}
 
class Circle extends Shape {
constructor(color: string, private radius: number) {
super(color);
}
getArea() { return Math.PI * this.radius ** 2; }
}
Breakdown
1
abstract getArea(): number;
Defines a method signature that must be implemented by any non-abstract child class.
2
printColor() { ... }
A concrete method that is inherited and usable by all subclasses.