Encapsulation in Java
Encapsulation means keep data private and change it only through safe methods. Imagine a locker. You don’t let everyone open the door and throw money in or out. You give deposit() and getBalance(). Inside deposit you can reject a negative amount. That is the whole pillar.
Let’s take this on the board. class BankAccount { private double balance; void deposit(double amt) { if (amt > 0) balance += amt; } double getBalance() { return balance; } }. Then BankAccount acc = new BankAccount(); acc.deposit(100); acc.deposit(-50); print acc.getBalance();. Output: 100. The -50 was ignored. Outside code cannot write acc.balance = -99 because balance is private. Compile error. That error is your friend.
If balance is public, any line in the project can smash the rules. That is the beginner mistake: “public for speed”. Interviews almost always ask this pillar. Show private field + validating method. Getters are OK; a clear action like deposit/withdraw is even better than a blank setBalance that accepts anything.
Encapsulation is not only private. It is private + a door that checks. A private field with a setter that accepts every value is a locked locker with the key taped on the door.
BankAccount
private balance
│ only via
▼
deposit() / getBalance()private balance + validating deposit() is the encapsulation demo.