# Encapsulation and Access Modifiers — Object-Oriented Programming (OOP)

Source: https://www.skillbyai.com/en/oop/e-encap

> Hide internal state and expose behaviour that protects invariants.

## Protecting the inside of an object

**Encapsulation** means bundling data with the methods that operate on it and **restricting direct access** to that data. The goal is to protect **invariants**, rules that must always hold, such as "balance is never negative" or "end date is after start date". Other code interacts only through a small **public interface**, so the class can change its internals later without breaking callers. **Access modifiers** enforce this. In Java: **`private`** (visible only inside the class), **package-private** (no modifier; visible within the package), **`protected`** (package plus subclasses) and **`public`** (everywhere). C++ has `private`, `protected` and `public` sections; C# adds `internal`. Python has no enforced privacy: a leading underscore (`_balance`) signals "internal by convention", and double underscores trigger name mangling. Make fields **private by default**, expose **operations** rather than raw setters, and add getters only for data callers genuinely need.

## Public interface, private state

Callers use public methods; private fields can change only through those methods.

![A shield-shaped capsule with a solid inner core and three small doors on its edge, arrows from outside entering only through the doors.](assets/figures/oop/section-2-map.svg) — Figure 2.1 — Encapsulation: a public interface around private state.

## Operations instead of setters

There is no setBalance; the only ways to change the balance enforce the rules.

```java
public class BankAccount {
    private final String accountNo;
    private long balancePaise;                     // private: no outside code can change it

    public BankAccount(String accountNo) {
        this.accountNo = accountNo;
    }

    public void deposit(long paise) {
        if (paise <= 0) throw new IllegalArgumentException("deposit must be positive");
        balancePaise += paise;
    }

    public boolean withdraw(long paise) {
        if (paise <= 0 || paise > balancePaise) return false;   // invariant: never negative
        balancePaise -= paise;
        return true;
    }

    public long getBalancePaise() { return balancePaise; }
    public String getAccountNo()  { return accountNo; }
}
```

## Getters and setters are not encapsulation

A class with private fields and a public getter and setter for each one is barely different from public fields: any code can still set any value. Real encapsulation exposes meaningful operations that keep the object valid.

**Quiz:** Which Java access modifier makes a member visible only inside its own class?

- [ ] public
- [ ] protected
- [x] private
- [ ] package-private (no modifier)

*Answer:* private. private restricts access to the declaring class.
