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.
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Awesome!
Completion rate improved to 5
Implementing Abstract Classes
Desliza para mostrar el menú
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.
¡Gracias por tus comentarios!