Encapsulation

Encapsulation is the concept of bundling the data (variables) and methods (functions) that operate on the data into a single unit or class. It is a way to restrict access to certain components and ensure that the object’s internal state cannot be directly accessed or modified from outside the class.

The idea behind encapsulation is to hide the internal state of an object and only expose a controlled interface for interacting with it. This is done through access modifiers like private, protected, and public.

Why is Encapsulation Important

  • Data Protection: It ensures that the internal data is protected and cannot be modified directly, reducing the risk of unauthorized access or changes.
  • Code Maintenance: You can modify the internal implementation of the class without affecting the users of the class (as long as the public methods remain consistent).
  • Validation: You can add validation and logic in setter methods to ensure that the object’s state remains consistent and valid.

How to Implement Encapsulation

  • Private Fields: Make the fields (variables) of the class private so they cannot be accessed directly from outside the class.
  • Public Methods (getters and setters): Provide public getter and setter methods to access and update the value of the private fields. This allows you to control how the data is modified.

Example

  • The name and age fields are private, so they cannot be accessed directly from outside the Person class.
  • The getName() and getAge() methods are public and allow reading the private fields.
  • The setName() and setAge() methods are public, but they provide controlled access to modify the fields. In the case of setAge(), it even has a validation to ensure that the age cannot be set to a negative number.