Implementing Abstract Classes
123456789101112131415161718192021222324252627abstract class Shape { abstract getArea(): number; abstract getPerimeter(): number; } class Rectangle extends Shape { width: number; height: number; constructor(width: number, height: number) { super(); this.width = width; this.height = height; } getArea(): number { return this.width * this.height; } getPerimeter(): number { return 2 * (this.width + this.height); } } const rect = new Rectangle(10, 5); console.log(rect.getArea()); // 50 console.log(rect.getPerimeter()); // 30
When you use an abstract class in TypeScript, you define methods that have no implementation, called abstract methods. These methods act as a contract: any subclass that extends the abstract class must provide concrete implementations for all abstract methods. This ensures that every subclass fulfills the required behaviors specified by the abstract class, helping you enforce consistent APIs and reducing errors from missing functionality. If a subclass does not implement all abstract methods, TypeScript will report a compilation error, preventing incomplete implementations.
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Can you explain the difference between abstract classes and interfaces in TypeScript?
Can you show an example of another shape class that extends the abstract Shape class?
What happens if I try to instantiate the abstract Shape class directly?
Awesome!
Completion rate improved to 5
Implementing Abstract Classes
Свайпніть щоб показати меню
123456789101112131415161718192021222324252627abstract class Shape { abstract getArea(): number; abstract getPerimeter(): number; } class Rectangle extends Shape { width: number; height: number; constructor(width: number, height: number) { super(); this.width = width; this.height = height; } getArea(): number { return this.width * this.height; } getPerimeter(): number { return 2 * (this.width + this.height); } } const rect = new Rectangle(10, 5); console.log(rect.getArea()); // 50 console.log(rect.getPerimeter()); // 30
When you use an abstract class in TypeScript, you define methods that have no implementation, called abstract methods. These methods act as a contract: any subclass that extends the abstract class must provide concrete implementations for all abstract methods. This ensures that every subclass fulfills the required behaviors specified by the abstract class, helping you enforce consistent APIs and reducing errors from missing functionality. If a subclass does not implement all abstract methods, TypeScript will report a compilation error, preventing incomplete implementations.
Дякуємо за ваш відгук!