TypeScript
Abstract Classes
Define abstract classes and abstract methods.
By EZ4Code Team
abstractclass
Code
abstract class Shape {
abstract area(): number;
describe(): string {
return `Area: ${this.area()}`;
}
}
class Circle extends Shape {
constructor(private radius: number) { super(); }
area() { return Math.PI * this.radius ** 2; }
}
class Rectangle extends Shape {
constructor(private w: number, private h: number) { super(); }
area() { return this.w * this.h; }
}
const c: Shape = new Circle(5);
console.log(c.describe());Explanation
Abstract classes cannot be instantiated directly; subclasses must implement abstract methods.