ITKokka
Lesson 1 ยท Note 4

Encapsulation

๐Ÿ“Œ The Short Note

Download

๐Ÿ“– Explanation

Encapsulation

Encapsulation means protecting internal data and controlling how it can be accessed or changed. A class wraps its data together with the methods that are allowed to touch that data.

  • Protect the data
  • Allow controlled access

Real World Example: Bank Account

Example: Bank Account

A BankAccount has internal data, its balance. Should any other part of the program be allowed to change it directly?

account.balance = 1000000;
account.balance = -5000;

No. Direct access like this is dangerous, nothing stops the balance from being set to a negative number or an unrealistic value. The balance must stay protected. Instead, the class exposes controlled actions: deposit(), withdraw(), getBalance(). Each method checks the rules (for example, rejecting a negative deposit) before it touches the data.

Encapsulation in Java

Code Example
class BankAccount {
    private double balance;

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
    public void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
        }
    }
    public double getBalance() {
        return balance;
    }
}

Public vs Private

  • private: only usable inside the class. Blocks direct access, this is how balance stays protected.
  • public: usable from outside the class. Gives controlled access, this is how deposit() and withdraw() reach the outside world safely.

Class Diagram

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚        BankAccount        โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ - balance: double         โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ + deposit(amount): void   โ”‚
โ”‚ + withdraw(amount): void  โ”‚
โ”‚ + getBalance(): double    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

- marks a private member, + marks a public member. balance stays hidden behind the class boundary, only the three public methods can reach it.

Key Idea: Encapsulation = Private Data + Public Methods.

Exam Focus Points

  • Encapsulation wraps data and methods together inside one class.
  • Private fields block direct outside access; public methods provide controlled access instead.
  • A well encapsulated class validates data (for example, rejecting an invalid withdrawal) before changing it.

Summary

  • Encapsulation protects an object's internal data from being changed directly.
  • Data is kept private, actions that are safe to expose are kept public.
  • Public methods act as checkpoints, they enforce the rules before the data changes.
  • Encapsulation = Private Data + Public Methods.
Share:
โ† The 4 Pillars of OOPAbstraction โ†’