OOP Fundamentals & UML
The four pillars (encapsulation, abstraction, inheritance, polymorphism) with code, interfaces vs abstract classes, composition vs inheritance, overloading vs overriding, class relationships (association, aggregation, composition, dependency, realization) and how to read and draw UML class and sequence diagrams.
The four pillars
Encapsulation
public class BankAccount {
private final String id;
private long balanceMinor; // hidden state
public BankAccount(String id) { this.id = id; }
public void deposit(long amount) {
if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
balanceMinor += amount;
}
public void withdraw(long amount) {
if (amount > balanceMinor) throw new IllegalStateException("insufficient funds");
balanceMinor -= amount; // invariant: never negative
}
public long getBalance() { return balanceMinor; } // read-only view
}
class BankAccount:
def __init__(self, account_id: str):
self._id = account_id
self._balance = 0 # "private" by convention
def deposit(self, amount: int) -> None:
if amount <= 0:
raise ValueError("amount must be positive")
self._balance += amount
def withdraw(self, amount: int) -> None:
if amount > self._balance:
raise ValueError("insufficient funds")
self._balance -= amount
@property
def balance(self) -> int:
return self._balance
Abstraction and polymorphism
Java
interface PaymentMethod {
PaymentResult pay(long amountMinor);
}
class CardPayment implements PaymentMethod {
public PaymentResult pay(long amount) { /* call card network */ return PaymentResult.ok(); }
}
class UpiPayment implements PaymentMethod {
public PaymentResult pay(long amount) { /* send UPI collect request */ return PaymentResult.ok(); }
}
class Checkout {
PaymentResult complete(Order order, PaymentMethod method) {
return method.pay(order.total()); // runtime dispatch: caller doesn't care which
}
}
Inheritance
Java
abstract class Account {
protected long balance;
abstract double monthlyInterestRate();
void applyInterest() { balance += Math.round(balance * monthlyInterestRate()); }
}
class SavingsAccount extends Account { double monthlyInterestRate() { return 0.004; } }
class CurrentAccount extends Account { double monthlyInterestRate() { return 0.0; } }
Interfaces vs abstract classes
| Interface | Abstract class | |
|---|---|---|
| State (fields) | no (constants only) | yes |
| Constructors | no | yes |
| Multiple inheritance | implement many | extend one |
| Method bodies | default/static methods | any |
| Use for | capabilities/roles | shared base implementation |
Composition over inheritance
Class relationships and UML notation
| Relationship | Meaning | UML | Example |
|---|---|---|---|
| Association | uses / knows about | solid line (→ for navigability) | Driver — Car |
| Aggregation | whole–part, independent lifecycle | hollow diamond ◇ at the whole | Team ◇— Player |
| Composition | whole–part, owned lifecycle | filled diamond ◆ at the whole | Order ◆— OrderLine |
| Inheritance (generalisation) | is-a | solid line, hollow triangle ▷ at parent | Car —▷ Vehicle |
| Realization | implements | dashed line, hollow triangle | CardPayment ┄▷ PaymentMethod |
| Dependency | temporarily uses | dashed arrow ┄> | ReportService ┄> PdfRenderer |
Multiplicity on line ends: 1, 0..1, *, 1..*.
A class diagram
Sequence diagrams
Show how objects collaborate over time for one use case — lifelines (vertical), messages (arrows), activation bars. Great for explaining flows like "user parks a car" in an interview.
Text
Driver -> EntryGate: arrive(vehicle)
EntryGate -> ParkingLot: findSpot(vehicle.type)
ParkingLot -> Floor[i]: findFree(type)
Floor[i] --> ParkingLot: spot
ParkingLot -> TicketService: issue(vehicle, spot)
TicketService --> EntryGate: ticket
EntryGate --> Driver: ticket, open barrier
Other OOP vocabulary
| Term | Meaning |
|---|---|
| Overloading | same name, different parameters (compile time) |
| Overriding | subclass redefines an inherited method (runtime) |
| Static vs instance members | belongs to the class vs to each object |
| Immutability | object state can't change after construction (final fields, no setters) — thread-safe by default |
| Cohesion | how focused a class is on one responsibility (want high) |
| Coupling | how much classes depend on each other's details (want low) |
equals/hashCode contract | equal objects must have equal hash codes (matters for HashMap/HashSet keys) |
| Generics | type-parameterised classes/methods (List<T>) |
| Enums | fixed sets of constants, can carry behaviour (great for states and types) |
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.