OOP Notes
Real-world encapsulation examples in Java, Python, and C++ — banking systems, game development, and configuration management.
class Inventory: MAX_WEIGHT = 100.0 MAX_SLOTS = 20
def __init__(self): self.__items = [] self.__total_weight = 0.0
@property def item_count(self): return len(self.__items)
@property def remaining_capacity(self): return self.MAX_WEIGHT - self.__total_weight
def add_item(self, item_name, weight, value): if len(self.__items) >= self.MAX_SLOTS: return False, "Inventory full" if self.__total_weight + weight > self.MAX_WEIGHT: return False, "Too heavy" if weight <= 0: return False, "Invalid weight"
self.__items.append({ "name": item_name, "weight": weight, "value": value }) self.__total_weight += weight return True, f"Added {item_name}"
def remove_item(self, item_name): for item in self.__items: if item["name"] == item_name: self.__items.remove(item) self.__total_weight -= item["weight"] return True, item return False, None
def get_items(self): """Return copies — prevent external modification""" return [item.copy() for item in self.__items]
def get_total_value(self): return sum(item["value"] for item in self.__items)
def get_heaviest_item(self): if not self.__items: return None return max(self.__items, key=lambda x: x["weight"]).copy()
inv = Inventory() inv.add_item("Iron Sword", 5.0, 150) inv.add_item("Health Potion", 0.5, 50) inv.add_item("Dragon Scale", 15.0, 500)
print(f"Items: {inv.item_count}") print(f"Total value: {inv.get_total_value()} gold") print(f"Remaining capacity: {inv.remaining_capacity} kg")
#include <iostream> #include <vector> #include <numeric> #include <algorithm>
class TemperatureSensor { private: std::string sensorId; std::vector<double> readings; double minValid, maxValid; int maxReadings;
bool isValidReading(double temp) const { return temp >= minValid && temp <= maxValid; }
void trimOldReadings() { while (readings.size() > maxReadings) { readings.erase(readings.begin()); } }
public: TemperatureSensor(std::string id, double min = -50, double max = 150) : sensorId(id), minValid(min), maxValid(max), maxReadings(1000) {}
bool recordReading(double temperature) { if (!isValidReading(temperature)) { std::cerr << "Invalid reading rejected: " << temperature << std::endl; return false; } readings.push_back(temperature); trimOldReadings(); return true; }
double getAverage() const { if (readings.empty()) return 0.0; double sum = std::accumulate(readings.begin(), readings.end(), 0.0); return sum / readings.size(); }
double getMax() const { if (readings.empty()) return 0.0; return *std::max_element(readings.begin(), readings.end()); }
double getMin() const { if (readings.empty()) return 0.0; return *std::min_element(readings.begin(), readings.end()); }
int getReadingCount() const { return readings.size(); } std::string getId() const { return sensorId; } };
public class Email { private String from; private List<String> to; private List<String> cc; private String subject; private String body; private List<String> attachments; private boolean sent;
private Email() { this.to = new ArrayList<>(); this.cc = new ArrayList<>(); this.attachments = new ArrayList<>(); this.sent = false; }
// Builder pattern — encapsulates construction public static class Builder { private Email email = new Email();
public Builder from(String address) { email.from = address; return this; }
public Builder to(String address) { email.to.add(address); return this; }
public Builder cc(String address) { email.cc.add(address); return this; }
public Builder subject(String subject) { email.subject = subject; return this; }
public Builder body(String body) { email.body = body; return this; }
public Email build() { if (email.from == null || email.to.isEmpty()) { throw new IllegalStateException("From and To are required"); } return email; } }
public void send() { if (sent) throw new IllegalStateException("Already sent"); System.out.println("Sending to: " + to); sent = true; }
public boolean isSent() { return sent; } }
// Usage Email email = new Email.Builder() .from("alice@example.com") .to("bob@example.com") .subject("Meeting Tomorrow") .body("Let's meet at 3pm.") .build();
email.send();
| Pattern | Purpose | Benefit |
|---|---|---|
| Private fields | Prevent direct access | Data integrity |
| Validation in methods | Reject invalid input | No corrupted state |
| Defensive copies | Prevent external modification | Internal safety |
| Computed properties | Derive values from state | Always consistent |
| Immutable after creation | Some fields never change | Predictable behavior |
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Encapsulation Examples.
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, examples, encapsulation examples
Related Object Oriented Programming (OOP) Topics