An object combines state with operations that preserve its rules
Object-oriented programming organizes related state and the operations that act on it behind an interface. A class defines the construction and behavior of its objects. An instance holds a particular object’s state, so two inventories can use the same class while recording different seat counts.
An interface describes the operations callers may perform and the promises those operations make. For an inventory, reserving seats should preserve a count between zero and capacity. That promise is an invariant, a rule that must hold before and after each completed operation. A method called reserve still needs to specify whether a request for too many seats is rejected or partially accepted.
Encapsulation groups the state with the operations that preserve its invariant. Callers request a reservation instead of reading a count and writing a new count themselves. Keeping the check and update together gives the implementation one place to enforce the rule and gives tests a stable behavior to examine.
How strongly a language enforces that boundary varies. In Java and C++, a field declared private can be read or written only by code inside its own class (and, in C++, by declared friends); the compiler rejects any other access. Python has no access modifiers: a leading underscore marks an attribute as internal by convention, and other code can still change it. In every language, grouping statements in one method does not make them atomic when several threads call it at once.
Compose an inventory with a replaceable allocation policy
Composition builds an object from collaborators with separate responsibilities. Here the inventory owns capacity and the reserved count. An allocation policy receives the requested amount and the free amount, then returns how many seats to accept. An all-or-nothing policy returns the full request when it fits and zero otherwise; a partial policy returns the smaller of the request and the available count.
This separation puts two kinds of change in different places. A product decision to permit partial groups changes the allocation policy. A correction to capacity checks changes the inventory. The inventory validates a policy’s result before updating its count, because even a replaceable collaborator must obey the capacity contract. Returning four accepted seats when only one remains is an implementation error.
Polymorphism lets the inventory call different policy implementations through the same operation. Both policies provide admit(requested, free), so the inventory has no need to inspect a policy’s class name. The caller can replace the policy while preserving the inventory object and its existing reservations.
Inheritance, overriding and dynamic dispatch
Inheritance declares one class a subtype of another: the subclass receives the parent’s fields and methods and may replace some of them. An abstract class declares methods without implementing them, so it cannot be instantiated; each concrete subclass must supply those methods. An interface declares operations without instance state. In Java a class can extend only one class but implement any number of interfaces, since interfaces carry no instance fields that could conflict.
A subclass overrides a method by defining one with the same name and parameters as its parent’s. When the inventory calls policy.admit(...), the language selects the implementation from the object’s actual class at run time, not from the declared type of the variable. This dynamic dispatch is what makes polymorphism work. Overloading is a different mechanism: two methods in one class share a name but take different parameters, and Java chooses between them when the code is compiled, from the argument types. Python has no overloading by parameter types; a later definition with the same name replaces the earlier one.
abstract class Policy { abstract int admit(int requested, int free);}class AllOrNothing extends Policy { @Override int admit(int requested, int free) { return requested <= free ? requested : 0; }}class Partial extends Policy { @Override int admit(int requested, int free) { return Math.min(requested, free); }}class Inventory { private final int capacity; private int used = 0; private Policy policy; Inventory(int capacity, Policy policy) { this.capacity = capacity; this.policy = policy; } int reserve(int requested) { int free = capacity - used; int accepted = policy.admit(requested, free); // dynamic dispatch if (accepted < 0 || accepted > Math.min(requested, free)) throw new IllegalStateException("policy broke its contract"); used += accepted; return accepted; } int reserve() { // an overload: same name, no parameters return reserve(1); }}Substituting a subclass is safe only when it keeps the parent’s promises, not merely its method names. This is the Liskov substitution principle: a Partial that returned more seats than were free would compile, yet break every caller that relied on the contract. Inheritance also couples a subclass to its parent’s internals, so a change to the parent can break subclasses that relied on how it worked. Prefer composition when one object only needs to use another’s behavior, and inheritance when the subclass genuinely is a kind of its parent and can honor all of its contract.
Connect each term to an observable action
| Term | Inventory example | Contract to check |
|---|---|---|
| Class and instance | Inventory defines behavior; A and B are separate objects | Reserving in A does not change B |
| Encapsulation | reserve and release own updates to the internal count | A rejected operation leaves state unchanged |
| Composition | An inventory contains an allocation policy | The policy cannot directly modify inventory state |
| Inheritance and overriding | AllOrNothing and Partial extend an abstract Policy and override admit | Each override keeps the parent’s promised result range |
| Polymorphism | Either policy answers admit(requested, free) | Each result is between zero and min(requested, free) |
| Invariant | Reserved count stays within capacity | 0 <= used <= capacity after each legal call |
A request for two seats behaves differently when only one remains
Start with inventory A at capacity three and reserve two seats. Its used count becomes two, leaving one free. Ask for two more under all-or-nothing allocation: the policy returns zero, so the operation admits zero and used stays two. This rejection preserves the previous state.
Switch to partial allocation and request two again. The policy returns min(2, 1) = 1; the inventory accepts one and used becomes three. The return value matters because a caller that treats any nonzero value as “the whole group is booked” would report two seats despite reserving only one.
Inventory B begins empty and is independent of A. Reserving one in B changes only B. Releasing more seats than an inventory currently holds is rejected, because a negative used count would invent free capacity. These are sequential operations; concurrent callers need synchronization around the check and update.
Reserve and release seats through a shared interface
Does swapping the allocation policy change an inventory’s existing state, and does one inventory ever affect the other? Reserve and release seats in A and B under each policy, including requests that do not fit.
Each object has capacity three. Calls run sequentially; the model has no persistence or concurrent writers.
Both objects are empty. Select an object and apply an operation.
Changing the policy leaves both inventories’ stored counts in place; only later admissions follow the new rule. A real booking product may prohibit partial group reservations entirely, and choosing that policy is part of the product contract.
Check a policy’s result before mutating the inventory
The same design in Python uses structural typing instead of a shared parent class. A Protocol names the method a policy must provide, and any object with a matching admit method qualifies. Type annotations let a static checker catch a mismatched caller, but Python does not enforce the policy’s return range, so reserve checks that range at run time.
class Allocation(Protocol): def admit(self, requested: int, free: int) -> int: ...class AllOrNothing: def admit(self, requested: int, free: int) -> int: return requested if requested <= free else 0class Partial: def admit(self, requested: int, free: int) -> int: return min(requested, free)class Inventory: def __init__(self, capacity: int, policy: Allocation): if type(capacity) is not int or capacity < 0: raise ValueError("invalid capacity") self._capacity = capacity self._used = 0 self.policy = policy @property def used(self) -> int: return self._used def reserve(self, requested: int) -> int: if type(requested) is not int or requested <= 0: raise ValueError("invalid request") free = self._capacity - self._used accepted = self.policy.admit(requested, free) if type(accepted) is not int or not 0 <= accepted <= min(requested, free): raise ValueError("policy violated its contract") self._used += accepted return accepted def release(self, amount: int) -> bool: if type(amount) is not int or amount <= 0: raise ValueError("invalid release") if amount > self._used: return False self._used -= amount return Truea = Inventory(3, AllOrNothing())b = Inventory(3, AllOrNothing())assert a.reserve(2) == 2assert a.reserve(2) == 0a.policy = Partial()assert a.reserve(2) == 1assert (a.used, b.used) == (3, 0)assert a.release(4) is Falseassert a.used == 3The constructor assigns the count on each instance, preventing accidental shared mutable state. reserve validates the input and the policy result before mutation, so errors preserve the old count. release returns a Boolean for a valid but unavailable release, while invalid amounts raise an error. These distinct outcomes let a caller handle malformed input separately from a rejected operation.
The object does not track reservation identities, persistence or ownership. A caller could release somebody else’s seats if the application exposed this aggregate operation directly. A production booking service needs identified holds, authorization and a database transaction or equivalent atomic operation for concurrent changes.
What stays true
For a valid inventory, 0 <= used <= capacity, and a rejected reservation or release leaves used unchanged.
Construction starts at zero. A reservation adds at most the free count, so used cannot pass capacity; a release subtracts only an amount it already holds, so used cannot go negative. This holds only while one operation finishes before the next begins: two concurrent requests can both read one free seat and both admit it. The class documents the rule, while synchronization or atomic storage must enforce it under concurrency.
Use objects where a stateful contract earns the structure
For a stateless calculation, a function is often enough. An object helps here because repeated calls must maintain the same count and preserve one rule. Composition adds one policy call per reservation but lets you test allocation independently and replace behavior without duplicating capacity checks.
Introducing a class for every noun can scatter one state transition across unnecessary layers, and deep inheritance hierarchies make a reader follow several files to learn what one method does. Keep related state together, expose the operations the caller actually needs, and add a new interface when there are concrete implementations or a useful testing boundary.
Object structure cannot replace a behavioral contract
Mutating before checking capacity.
- Where it breaks
- With capacity 3 and used 2, adding a request of 2 first produces used 4 even if the method later reports failure.
- The fix
- Validate the admitted amount before changing the count.
Treating a partial result as a complete reservation.
- Where it breaks
- With one seat free, a request for two returns 1; the caller reports two reserved seats.
- The fix
- Return and inspect the exact admitted quantity, or require all-or-nothing behavior.
Confusing overloading with overriding.
- Where it breaks
- A subclass of AllOrNothing declares admit(long requested, int free) intending to change its rule; Java treats it as a new overload, so the inventory keeps calling AllOrNothing’s admit(int, int).
- The fix
- Match the parent’s parameters exactly and mark the method with @Override so the compiler rejects a mismatch.
Assuming instance isolation when mutable state is shared.
- Where it breaks
- If A and B use the same mutable count container, reserving two in A also makes B report two.
- The fix
- Initialize instance state in the constructor and test two objects together.
Assuming encapsulation makes check-and-update atomic.
- Where it breaks
- Two callers each observe one free seat and each accept one, creating two reservations against capacity one.
- The fix
- Make the state transition atomic at the shared storage or synchronization boundary.
Extend the object contract across failures and storage
Related topics
- Design principles →
Divide responsibilities and dependencies so changes stay local.
- Design interview formats →
Use the contract, state transitions and rejected calls as evidence in an LLD interview.
- Idempotency keys →
Prevent a retried reservation from applying the same intended change twice.
Further reading
- Oracle Java Tutorials: Object-Oriented Programming Concepts Objects, classes, inheritance, interfaces and packages, explained without assuming prior OOP experience. docs.oracle.com (opens in a new tab)
- Python tutorial: Classes Instances, attributes, inheritance and the distinction between class and instance variables in Python. docs.python.org (opens in a new tab)