Encapsulation in Java — Java Technical Interview Questions & Answers
Encapsulation in Java
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()Technical Interview Tip: private balance + validating deposit() is the encapsulation demo.
Code Examples for Encapsulation in Java
Example
class Account {
private int balance = 0;
public int getBalance() { return balance; }
public void deposit(int amount) {
if (amount > 0) balance += amount;
}
}
public class Main {
public static void main(String[] args) {
Account a = new Account();
a.deposit(100);
System.out.println(a.getBalance());
}
}Encapsulation in Java — output: 100. Main cannot write a.balance — it is private. deposit(100) updates it; getBalance reads it.
How to Explain Encapsulation in Java to an Interviewer
What is encapsulation?
Hide data Change only through methods
Why private fields?
Outside code cannot break rules
Show a tiny example.
private balance deposit() validates getBalance()