Encapsulation in TypeScript

Introduction to Encapsulation

Welcome back! We're shifting our focus to another essential concept in Object-Oriented Programming (OOP): encapsulation. Encapsulation helps us bundle the data (variables) and methods (functions) that operate on the data into a single unit called a class. It also restricts access to some of the object's components, ensuring data integrity and security.

In real-world scenarios, encapsulation is like how a car hides its engine details from the driver. You can drive the car using the steering wheel and pedals (public interface), but you don't need direct access to the engine's inner workings (private details). This protects the engine from accidental misuse and keeps the car running smoothly.

Achieving Encapsulation

Encapsulation is a fundamental concept in object-oriented programming that involves bundling the data (variables) and methods that operate on the data into a single unit or class. This helps protect the data from unauthorized access and modification.

In TypeScript, encapsulation is achieved using access modifiers:

  1. private: Members marked as private can only be accessed within the same class. This is the most common way to restrict access to sensitive data and implementation details.
  2. protected: Members marked as protected can be accessed within the class and by subclasses, but not from outside these classes. This is useful when you want to allow derived classes to interact with certain data or methods, but still keep them hidden from the outside world.
  3. public: Members marked as public (the default) can be accessed from anywhere.

Encapsulation enhances the modularity, maintainability, and security of your code by preventing unauthorized access and modifications to an object's internal state.

Example: Encapsulation in Practice

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal