Typescript Abstract Class
Last Updated :
18 Jul, 2024
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:
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 {
abstract makeSound(): void; // Abstract method
move(): void {
console.log("Moving...");
}
}
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 Classes
This 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.
JavaScript
abstract class Animal {
constructor(public name: string) { }
abstract makeSound(): void;
move(): void {
console.log(`${this.name} is moving.`);
}
}
class Dog extends Animal {
makeSound(): void {
console.log(`${this.name} says: Woof!`);
}
}
class Cat extends Animal {
makeSound(): void {
console.log(`${this.name} says: Meow!`);
}
}
const dog = new Dog('Buddy');
const cat = new Cat('Whiskers');
dog.makeSound();
dog.move();
cat.makeSound();
cat.move();
Output:
Buddy says: Woof!
Buddy is moving.
Whiskers says: Meow!
Whiskers is moving.
Advanced Usage with Abstract Methods
This 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.
JavaScript
abstract class Shape {
abstract area(): number;
abstract perimeter(): number;
describe(): void {
console.log(`Area: ${this.area()},
Perimeter: ${this.perimeter()}`);
}
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
area(): number {
return Math.PI * this.radius * this.radius;
}
perimeter(): number {
return 2 * Math.PI * this.radius;
}
}
class Rectangle extends Shape {
constructor(private width: number, private height: number) {
super();
}
area(): number {
return this.width * this.height;
}
perimeter(): number {
return 2 * (this.width + this.height);
}
}
const circle = new Circle(5);
const rectangle = new Rectangle(10, 20);
circle.describe();
rectangle.describe();
Output:
Area: 78.53981633974483, Perimeter: 31.41592653589793
Area: 200, Perimeter: 60
Benefits of Using Abstract Classes
- Code Reusability: Abstract classes allow you to define methods that can be shared across multiple derived classes, reducing code duplication.
- Encapsulation: Abstract classes can hide the implementation details while exposing only the necessary methods that derived classes need to implement.
- Polymorphism: Abstract classes enable polymorphism, allowing you to write more flexible and extensible code.
Similar Reads
What are Abstract Classes in TypeScript? An abstract class in TypeScript serves as a blueprint for other classes and cannot be instantiated directly. It may include abstract methods without implementation, which must be defined in any subclass.Additionally, it can contain concrete methods with implementations, properties, and other members
4 min read
Abstract Classes in Python In Python, an abstract class is a class that cannot be instantiated on its own and is designed to be a blueprint for other classes. Abstract classes allow us to define methods that must be implemented by subclasses, ensuring a consistent interface while still allowing the subclasses to provide speci
5 min read
Abstract Classes in PHP Abstract classes in PHP are classes that may contain at least one abstract method. Unlike C++, abstract classes in PHP are declared using the abstract keyword. The purpose of abstract classes is to enforce that all derived classes implement the abstract methods declared in the parent class. An abstr
2 min read
C# Abstract Class In C#, an abstract class is a class that cannot be instantiated directly. Abstract classes are used when we want to define a common template for a group of related classes but leave some methods or properties to be implemented by derived classes.An abstract class cannot be directly instantiated. We
6 min read
Scala | Abstract Type members A member of a class or trait is said to be abstract if that particular member does not have a complete definition in the class. These Abstract members are always implemented in any sub-classes of the class under which it is defined. These kinds of declaration are allowed in many programming language
4 min read
Constructor in Java Abstract Class Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor. So if we do not define any constructor inside the abstract class then JVM (Java Virtual Machine) will g
4 min read
TypeScript Generic Classes Generics in TypeScript allow us to create reusable and type-safe components. Generic classes help in defining a blueprint that can work with different data types without sacrificing type safety. They enable better code reusability and flexibility by allowing us to define type parameters that will be
5 min read
How to Test an Abstract Class with JUnit? Testing abstract classes in Java can be challenging due to their incomplete nature. They cannot be instantiated directly. Abstract classes are often used as the blueprint for the other classes. They can include abstract methods, which lack implementations, as well as concrete methods that are fully
7 min read
How to Extend abstract class with Generics in Typescript ? In Typescript, an abstract class is the base class that is inherited by other classes without having to define its members. Generic is the feature with which you can create a variable that represents a type in classes, functions, and type aliases that don't need to define the types that they use exp
3 min read
Abstract types vs Generics in Scala In this discussion, we will explore abstract types and generics in Scala, highlighting their differences. Abstract types are types that include abstract members, while generics are types that can take other types as parameters. Let's delve into the disparities between these two concepts. Scala Abstr
2 min read