Abstract class with an abstract method in TypeScript
13 An abstract shape with a required perimeter
fairWrite an abstract shape class with a colour and an abstract method for the perimeter. Write a circle and a rectangle that supply real implementations.
Stuck? Three hints, smallest first
- 1.
abstract class Shapecannot be instantiated;new Shape(...)is a compile error. - 2. An
abstractmethod has no body. A subclass that forgets it will not compile. - 3. The parent can still hold shared code, which is why abstract classes beat plain interfaces here.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
abstract class Shape {
constructor(public colour: string) {}
// No body. Every concrete subclass must supply one.
abstract getPerimeter(): number;
// Shared code, written once, using the abstract member.
describe(): string {
return `${this.colour} ${this.constructor.name}, perimeter ${this.getPerimeter().toFixed(2)}`;
}
}
class Circle extends Shape {
constructor(colour: string, public radius: number) {
super(colour);
}
override getPerimeter(): number {
return 2 * Math.PI * this.radius;
}
}
class Rectangle extends Shape {
constructor(colour: string, public width: number, public height: number) {
super(colour);
}
override getPerimeter(): number {
return 2 * (this.width + this.height);
}
}
// new Shape('red'); // error: Cannot create an instance of an abstract class.
const shapes: Shape[] = [new Circle('red', 3), new Rectangle('blue', 4, 5)];
for (const s of shapes) console.log(s.describe());
const total = shapes.reduce((n, s) => n + s.getPerimeter(), 0);
console.log('total perimeter:', total.toFixed(2));
test('circle perimeter', Number(shapes[0]?.getPerimeter().toFixed(2)), 18.85);
test('rectangle perimeter', shapes[1]?.getPerimeter(), 18);
test('shared describe used the subclass answer', shapes[1]?.describe(), 'blue Rectangle, perimeter 18.00');
test('total across both', Number(total.toFixed(2)), 36.85);
Output
describe() is the reason to use an abstract class rather than an interface. It is written once in the parent and calls getPerimeter(), which does not exist yet at that point. The parent depends on a promise the children are forced to keep.