Q.What is encapsulation? Explain how making a field private with public getter and setter methods protects an object's data, with a short example.
Meaning. Encapsulation is one of the core ideas of object-oriented programming. It means keeping the data (fields) and the code that operates on it (methods) together inside one class, and hiding the data from the outside world so it cannot be misused.
The standard technique has two steps:
- declare the fields
privateso no outside code can touch them, and - provide
publicmethods — a getter to read a field and a setter to change it — so every access passes through code the class controls.
Example:
class Account {
private double balance; // hidden data
public double getBalance() { // getter: read only
return balance;
}
public void deposit(double amount) { // setter with a rule
if (amount > 0) { // reject invalid values
balance = balance + amount;
}
}
}
How it protects the data. Because balance is private, code elsewhere cannot write a.balance = -5000; — the compiler forbids it. The only way to change the balance is through deposit(...), which refuses a negative amount. So the object can never be left in an invalid state.
Extra benefit. If the rule changes later (say a deposit must be at least ₹100), you edit only the deposit method and the whole program obeys the new rule — because nothing else was ever allowed to touch balance.
Encapsulation wraps data and methods together and hides the data. Making balance private with a public deposit setter that checks the amount means invalid values are rejected and the object's data stays valid — and rules can be changed in one place.
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.