Published on

Encapsulation

Authors
  • avatar
    Name
    Iraianbu A
    Twitter

Table of Contents

Introduction

Encapsulation is one of the four fundamental principles of object-oriented programming (OOP). It is the practice of bundling data (attributes) and methods (functions) that operate on the data into a single unit, called a class while restricting direct access to the internal details of the class. It means wrapping the data (attributes) and methods (functions) together into a single unit.

Encapsulation can be achieved by:

  • Access modifiers (public, private, protected)
  • Getters and setters
  • Data Hiding

Encapsulation helps in data protection , modularity and maintainability of the code.

Key Benefits

  • Data Hiding : Prevent direct access to sensitive data.
  • Increased Security : Controls how the data is accessed or modified.
  • Improved Code Maintainability : Allows changes without affecting other parts of the code.
  • Better Modularity : Allows the class to be used independently of other classes.

Using Access Modifiers

We can use access modifiers to control the visibility of the data and methods.

Using Getters and Setters

Encapsulation ensure that the data cannot be directly accessed but must be retrieved or modified through methods.

Data Hiding

Encapulsation helps in hiding the implementation details while exposing only necessary methods.

Reason

  1. Prevents direct modification
  2. Ensures data integrity.

Java

class BankAccount {
    private double balance;
    private String accountNumber;

    // Constructor
    public BankAccount(double balance, String accountNumber) {
        this.balance = balance;
        this.accountNumber = accountNumber;
    }

    // Getter method
    public double getBalance() {
        return balance;
    }

    // Setter method
    public void deposit(double amount) {
        balance += amount;
        System.out.println("Deposited " + amount + " to account " + accountNumber);
    }

    public static void main(String... args) {
        BankAccount account = new BankAccount(1000, "1234567890");
        account.deposit(500);
        System.out.println("Balance: " + account.getBalance());
    }
}

Output

Deposited 500.0 to account 1234567890
Balance: 1500.0

Real world examples

  1. Banking Applications - Protecting sensitive financial data.
  2. Healthcare Applications - Protecting patient records.
  3. E-commerce Platforms - Hiding payment processing details

References