OOP Notes
Understand encapsulation — the OOP principle of bundling data with methods and restricting direct access to an object
// Anywhere in the codebase... UserAccount acc = new UserAccount(); acc.balance = -50000; // Negative balance? Sure, why not! acc.password = ""; // Empty password? No problem! acc.isActive = false; // Deactivate without proper procedure? Done!
// WITH encapsulation — controlled and safe class UserAccount { private String username; private String password; private double balance; private boolean isActive;
public UserAccount(String username, String password) { if (username.length() < 3) throw new IllegalArgumentException("Username too short"); if (password.length() < 8) throw new IllegalArgumentException("Password too weak"); this.username = username; this.password = hashPassword(password); this.balance = 0; this.isActive = true; }
public boolean deposit(double amount) { if (amount <= 0) return false; if (!isActive) return false; balance += amount; return true; }
public boolean withdraw(double amount) { if (amount <= 0) return false; if (amount > balance) return false; if (!isActive) return false; balance -= amount; return true; }
public double getBalance() { return balance; // Read-only access }
private String hashPassword(String raw) { // Internal implementation — hidden from outside return Integer.toHexString(raw.hashCode()); } }
## The Two Aspects of Encapsulation
### 1. Data Bundling
Related data and methods live together in one class. Everything about a `UserAccount` — the data it holds and the operations it supports — is in one place.
### 2. Access Restriction
Internal state is hidden behind private access modifiers. The outside world interacts only through a controlled public interface.class Thermostat: """Encapsulates temperature control logic"""
def __init__(self, target_temp=72): self.__current_temp = 68 # Private: sensor reading self.__target_temp = target_temp # Private: desired temp self.__is_heating = False # Private: system state self.__is_cooling = False
# Public interface — what users can do def set_target(self, temp): """Controlled access with validation""" if temp < 50 or temp > 90: raise ValueError("Temperature must be between 50°F and 90°F") self.__target_temp = temp self.__adjust()
def get_status(self): """Safe read access to state""" status = "idle" if self.__is_heating: status = "heating" if self.__is_cooling: status = "cooling" return { "current": self.__current_temp, "target": self.__target_temp, "status": status }
# Private implementation — hidden logic def __adjust(self): """Internal logic the user never sees""" diff = self.__target_temp - self.__current_temp self.__is_heating = diff > 2 self.__is_cooling = diff < -2
thermo = Thermostat(72) thermo.set_target(75) print(thermo.get_status())
Cannot do: thermo.__current_temp = 200 (AttributeError)
| 1. **Data Integrity** | Invalid states are impossible when access is controlled |
| 2. **Flexibility to Change** | You can rewrite internal logic without breaking external code |
| 3. **Simplified Interface** | Users see only what they need — not 50 internal variables |
| 4. **Debugging** | When a value is wrong, you know it was changed through one of the setter methods |
| 5. **Security** | Sensitive data (passwords, keys) can't be accessed directly |
┌─────────────────────────────────────────┐ │ PUBLIC INTERFACE │ │ (what other code can see and use) │ │ │ │ deposit(), withdraw(), getBalance() │ ├─────────────────────────────────────────┤ │ PRIVATE IMPLEMENTATION │ │ (hidden internal details) │ │ │ │ balance, password, hashPassword(), │ │ validateTransaction(), auditLog │ └─────────────────────────────────────────┘
You can completely rewrite the implementation (change database, add encryption, restructure data) without affecting any code that uses the class, as long as the public interface stays the same.
## Common Mistakes
1. **Making everything public "for convenience"** — this defeats the entire purpose
2. **Providing getters AND setters for everything** — if every field has both, you basically have no encapsulation
3. **Exposing internal collections** — returning a private list lets outsiders modify it
4. **Breaking encapsulation "just this once"** — one violation invites many more
5. **Confusing encapsulation with just using private** — it's also about having a coherent public interface
## Key Takeaways
- Encapsulation = **bundling** data with methods + **hiding** internal state
- Private fields + public methods = **controlled access**
- External code uses the **interface**, not the implementation
- Encapsulation enables **safe modification** of internals without breaking clients
- It's the foundation of maintainable, reliable OOP code
- Think: "What does the outside world NEED to know?" — everything else should be privateExam Focus
Revise definitions, diagrams, examples, and short-answer points for Introduction to Encapsulation.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Object Oriented Programming (OOP) topic.
Search Terms
object-oriented-programming, object oriented programming (oop), object, oriented, programming, encapsulation, introduction, introduction to encapsulation
Related Object Oriented Programming (OOP) Topics