Storing data in a class is only half the job. The other half is deciding who gets to change that data, and how. If any part of the program can write any value into any field, one careless line can leave an object in a state that should never exist, like a metro card with a balance of minus 500 rupees. Encapsulation is how you stop that from happening.
In one line: keep the data and the methods that use it together, and let only that class touch the data.
Your Hyderabad Metro card
The balance sits on a chip inside the card. You cannot open it up and type in a new number. There are only two ways in: recharge it at the counter, or tap it at the gate. The gate never even reads your balance. It just asks the card, "can this person enter?" Because every change goes through those two doors, the metro can trust that no card is carrying a fake or negative balance.
The MetroCard keeps its data inside; outside code can only use the public methods
1. What Is Encapsulation?
Encapsulation means a class owns its data. Two ideas go into that.
First, bundling. The data (balance, trips) and the methods that work on it (recharge(), payFare()) live in one class instead of being scattered around the program.
Second, information hiding. The fields are private. The rest of the program only sees a handful of public methods, and those methods decide which changes are allowed.
The rules an object must never break are called its invariants. For the metro card there are two: the balance is never negative, and it never goes above Rs.3000. Encapsulation is how a class protects its invariants. If the only way to change the balance runs through methods that check those rules, the rules simply cannot be broken.
2. Why Encapsulation Matters
The biggest win is that the object is always in a valid state. Every change goes through a method that checks it first.
It also keeps each rule in one place. The "you need at least Rs.20 to enter" rule lives inside MetroCard. Without encapsulation every gate, counter and mobile app would carry its own copy of that check, and sooner or later one of them would get it wrong.
You are also free to change the inside later. You could store the balance in paise, or fetch it from a server, and code that only calls getBalance() would not notice.
Debugging gets easier too. If the balance is wrong, only a few methods could have changed it. With a public field, the bug could be on any line of the codebase.
Finally, sensitive data such as a password hash never has to leave the object. The login example later in this article shows how.
3. How Encapsulation Is Achieved
3.1 Access Modifiers
Access modifiers decide who can see a field or a method. A good default: make everything private, and make something public only when another class genuinely needs it.
| Access | Java |
|---|---|
| Private (this class only) | private |
| Protected (class + subclasses) | protected |
| Public (everyone) | public |
| Controlled getter / setter | getX() / setX() |
Java enforces these at compile time. Code that tries to read a private field from outside the class simply does not compile.
3.2 Without vs With Encapsulation
Here is an air conditioner with public fields. Nothing stops the program from setting a temperature that makes no sense:
It compiles, it runs, and the object is now holding nonsense. Now let the class own its data. The field becomes private and the setter checks every new value before accepting it:
Output
AC set to 22 °C
Rejected: Temperature must be between 16 and 30 °C
AC still at 22 °C The bad value is turned away and the AC stays at 22 °C. The calling code did not have to remember any rule; the class enforced it.
4. Encapsulation in Practice: Metro Card
Time for a complete class. A MetroCard follows three rules: a recharge must be a positive amount, the balance can never go above Rs.3000, and a fare can never push it below zero. In the class diagram, - marks what is hidden and + marks what is public. The underlined members are static, shared by every card.
Class diagram of MetroCard: private data, public behavior
Every public method checks the rules before it touches the data. This is what happens inside payFare():
payFare() validates first and changes state only when every check passes
Output
Error: Recharge amount must be positive
Error: Low balance for Ameerpet -> LB Nagar
Card HYD-1029 balance: Rs.25
Can enter gate: true
Ameerpet -> HITEC City (Rs.35)
Miyapur -> Ameerpet (Rs.40) Why This Design Works
Both invalid requests are refused, and the balance is still a correct Rs.25 at the end. No method on this class can break an invariant.
Money is kept as whole rupees in an int, not a double. Floating-point numbers cannot store values like 0.1 exactly, which is why real payment systems keep money as an integer in the smallest unit.
The gate asks a question instead of reading data. canEnter() keeps the Rs.20 rule inside the card, so if the metro raises the minimum to Rs.30, one line changes.
And there is no setBalance(). A setter would let anyone write any number. The balance changes only through the two operations that mean something: recharge() and payFare().
5. Do Not Leak Your Internals
Marking a field private is not enough if a getter hands out the object itself. Return the real internal list, and the caller can change it behind your back. This is one of the most common encapsulation bugs, both in interviews and in production code.
Output
Leaky card trips: [Fake trip (Rs.0)]
Safe card refused the edit In Java, return List.copyOf(list) or Collections.unmodifiableList(list) instead of the list itself. The same goes for any other mutable object you store, such as a Date or one of your own classes: make a defensive copy when it comes in and when it goes out.
6. Practical Example: Login with Account Lockout
Encapsulation is a security tool as well. A UserAccount must never expose its password, and it has to lock itself after three wrong attempts in a row so nobody can sit there guessing. If failedAttempts or locked were public, any code could quietly reset them and the lockout would be worthless.
Decision flow inside login(): the lockout rule lives entirely inside UserAccount
Output
Attempt 1: failed, 2 attempt(s) left
Attempt 2: failed, 1 attempt(s) left
Attempt 3: failed, account locked
Attempt 4: failed, account locked
Password reset for ravi_k
Attempt 5: success Why This Design Works
The plain password is never stored. The class keeps only a hash, and there is no getter for it, so nobody can read it, print it or log it by mistake.
The lockout cannot be skipped. failedAttempts and locked are private, and the only way to unlock the account is resetPassword(), which the system calls after it has verified the user, say with an OTP.
The helpers stay hidden. hash() and requireStrong() are private, so if you later move from SHA-256 to bcrypt or Argon2 (which is what a real system should use, because they are slow and salted), no caller has to change.
The hashes are compared with MessageDigest.isEqual, which takes the same time whether the first byte or the last byte differs. That way an attacker learns nothing from how long the check took.
7. Getters and Setters Are Not Automatically Encapsulation
A lot of people make every field private and then generate a getter and setter for each one. It looks encapsulated, but it is really a public field with extra typing. Compare these two ways of charging a fare:
// Asking for data, then deciding outside the class (rules leak out)
if (card.getBalance() >= fare) {
card.setBalance(card.getBalance() - fare);
}
// Telling the object what to do (rules stay inside)
card.payFare("Ameerpet", "HITEC City", fare); The first version pushes the "enough balance" rule out into the caller, forgets to record the trip, and still allows setBalance(-500) from anywhere. The second follows "Tell, Don't Ask": you tell the object what you want and let it apply its own rules.
So add a getter only when another class really needs to read the value. Add a setter only when changing the value freely is a genuine use case, and validate inside it. Wherever you can, prefer methods that mean something, like recharge(), payFare() or lock(). And mark fields that never change after construction, like cardId, as final.
8. Common Mistakes
- Making fields public "for convenience". Any code can now write any value, and the class can no longer promise anything.
- Writing a setter for every field. That hides nothing. Expose behavior, not raw data.
- Setters that do not validate. If
setTemperature(-40)succeeds, you are no better off than with a public field. - Returning internal collections or mutable objects. The caller can change your private state through the reference.
- Leaving validation to the caller. If callers have to remember to check first, one of them will forget. Put the check inside the method.
- Exposing sensitive data. Passwords, tokens and full card numbers should never have a getter or show up in
toString()or a log line.
Summary
Encapsulation keeps data together with the methods that use it, and hides that data so only the class can change it. The point is to protect the object's invariants: an encapsulated object cannot be pushed into an invalid state.
In practice that means private fields by default, validation on every change, and methods that describe real behavior instead of raw setters. Do not hand out your internal collections; return copies or read-only views. You also get better security, easier debugging, and the freedom to change the implementation later without breaking anyone.
Next comes abstraction, which hides not just the data but the complexity of how something works.