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 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
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
6 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
TypeScript Construct Signatures
TypeScript Construct Signatures define the shape of a constructor function, specifying the parameters it expects and the type of object it constructs. They use the new keyword in a type declaration to ensure the correct instantiation of classes or objects. Syntaxtype Constructor = new (param1: Type1
3 min read
TypeScript Object Types
TypeScript object types define the structure of objects by specifying property types, ensuring type safety and clarity when passing objects as function parameters. Optional properties, denoted with a ? provide flexibility for objects with varying properties. This approach enhances code robustness by
3 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
Interfaces in TypeScript
TypeScript is a statically typed superset of JavaScript that adds optional types, classes, interfaces, and other features to help developers build robust and maintainable applications. One of the most powerful features of TypeScript is interfaces, which allow you to define the structure of objects,
4 min read
Data types in TypeScript
In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity. Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Pri
3 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