Lessons · TypeScript · abstract classes
An abstract class shares real code and demands the rest
abstract class Shape cannot be instantiated. It can carry real methods every subclass shares, and abstract members each subclass must supply.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
label() written once on Shape, calling this.area() that each shape supplies, is how a drawing library, a payment provider family or a report format family avoids copying the shared half into every member.
How to think about it
Put the shared behaviour in the abstract class, declare what varies as abstract, and let each subclass fill in only that. If nothing is shared, an interface is enough.
Worked example
abstract class Shape {Cannot be instantiated. constructor(public name: string) {}abstract area(): number;Every subclass must supply this.
label(): string { return this.name + ' with area ' + this.area(); }Shared, written once.}
class Square extends Shape { constructor(private side: number) { super('square'); } area() { return this.side * this.side; }The one thing a Square adds.}
console.log(new Square(3).label());square with area 9
Your turn
Declare the method every subclass must supply.
abstract class Shape {
area(): number;
}Solve one with the compiler running
The trap
Writing new Shape('x'). The compiler refuses: cannot create an instance of an abstract class. Build a subclass instead.