![]() |
TypeScript, a superset of JavaScript, introduces many features to improve code organization, readability, and maintainability. One of these features is abstract classes. This article will explain what abstract classes are, how they work, and how to use them effectively in your TypeScript projects. These are the topics that we are going to discuss: Table of Content What is an Abstract Class?An abstract class is a class that cannot be instantiated directly. Instead, it serves as a blueprint for other classes. Abstract classes are used to define common behaviors that multiple derived classes can share. They can contain both implementation and abstract (unimplemented) methods. How to define an Abstract Class?To define an abstract class in TypeScript, use the abstract keyword. Here’s a basic example: abstract class Animal { In this example, Animal is an abstract class with an abstract method makeSound and a regular method move. The makeSound method does not have an implementation, so any class that extends Animal must provide an implementation for makeSound. Basic Usage of Abstract ClassesThis TypeScript code defines an abstract Animal class with a constructor that sets the name property, an abstract makeSound() method, and a move() method that logs a movement message. The Dog and Cat classes extend Animal, implementing the makeSound() method with species-specific sounds. Instances of Dog and Cat are created, and their makeSound() and move() methods output appropriate messages for each animal. Example: This example illustrates the basic usage of abstract classes.
Output: Buddy says: Woof!
Buddy is moving.
Whiskers says: Meow!
Whiskers is moving. Advanced Usage with Abstract MethodsThis TypeScript code defines an abstract Shape class with abstract methods area() and perimeter() , and a describe() method to log these values. The Circle and Rectangle classes extend Shape , implementing their respective area and perimeter calculations based on given dimensions (radius for circle, width and height for rectangle). Instances of Circle and Rectangle are created, and their describe() method outputs calculated area and perimeter values. Example: This example shows the use of abstract class and the abstract function.
Output: Area: 78.53981633974483, Perimeter: 31.41592653589793
Area: 200, Perimeter: 60 Benefits of Using Abstract Classes
|
Reffered: https://www.geeksforgeeks.org
TypeScript |
Related |
---|
|
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 22 |