{}DSA Atlas

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.

Beginner5 interview questions

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

InterfaceAbstract class
State (fields)no (constants only)yes
Constructorsnoyes
Multiple inheritanceimplement manyextend one
Method bodiesdefault/static methodsany
Use forcapabilities/rolesshared base implementation

Composition over inheritance

Inheritance explosion Car ElectricCar PetrolCar E-Sport E-Family P-Sport P-Family every new dimension multiplies classes Composition Carengine, style «interface» EngineElectric · Petrol «interface» StyleSport · Family N + M small classes, combined at runtime
Prefer has-a over is-a when behaviour varies along several dimensions.

Class relationships and UML notation

RelationshipMeaningUMLExample
Associationuses / knows aboutsolid line (→ for navigability)Driver — Car
Aggregationwhole–part, independent lifecyclehollow diamond ◇ at the wholeTeam ◇— Player
Compositionwhole–part, owned lifecyclefilled diamond ◆ at the wholeOrder ◆— OrderLine
Inheritance (generalisation)is-asolid line, hollow triangle ▷ at parentCar —▷ Vehicle
Realizationimplementsdashed line, hollow triangleCardPayment ┄▷ PaymentMethod
Dependencytemporarily usesdashed arrow ┄>ReportService ┄> PdfRenderer

Multiplicity on line ends: 1, 0..1, *, 1..*.

A class diagram

Order - id: String- status: OrderStatus + addItem(p, qty)+ total(): Money OrderLine - quantity: int- unitPrice: Money + subtotal(): Money 11..* Product - sku: String- price: Money * «interface»PaymentMethod+ pay(amount) CardPayment UpiPayment uses (dependency) filled diamond = composition (lines die with the order) · dashed + hollow triangle = implements
Visibility: + public, - private, # protected, ~ package.

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

TermMeaning
Overloadingsame name, different parameters (compile time)
Overridingsubclass redefines an inherited method (runtime)
Static vs instance membersbelongs to the class vs to each object
Immutabilityobject state can't change after construction (final fields, no setters) — thread-safe by default
Cohesionhow focused a class is on one responsibility (want high)
Couplinghow much classes depend on each other's details (want low)
equals/hashCode contractequal objects must have equal hash codes (matters for HashMap/HashSet keys)
Genericstype-parameterised classes/methods (List<T>)
Enumsfixed sets of constants, can carry behaviour (great for states and types)

Interview questions

0 / 5 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.