UML class diagrams and relationships
A class diagram shows the classes, their fields and methods, and how they relate to each other.
Why it matters
In an interview, you need to show the structure of your design quickly, before coding. A clear diagram lets the interviewer follow you and correct you early.
The idea
In LLD interviews you sketch the main classes and relationships before coding. The relationships: association (uses or knows about), aggregation (has, but the part can exist alone), composition (owns; the part dies with the whole), inheritance (is-a) and realisation (implements an interface). Multiplicity (1, 0..1, *) says how many.
A family tree combined with an organisation chart: who is a kind of what, and who belongs to whom.
A family tree records what already happened. A class diagram is a draft: keep it simple, and change it as your design improves.
How it works
- Draw a box for each class: its name at the top, key fields in the middle, key methods at the bottom.
- Connect the boxes with the right line: a filled diamond for 'owns', an empty diamond for 'has', a triangle arrow for 'is a', and a dashed triangle arrow for 'implements'.
- Add numbers at the line ends: 1, 0..1 or * (many).
- Talk through one use case on the diagram before you write code.
Example
Parking lot: ParkingLot owns Floors (composition), a Floor owns Spots (composition), a Spot holds 0 or 1 Vehicle (association), and Car, Truck and Bike are kinds of Vehicle (inheritance).
Key points
- Composition (filled diamond): the owner controls the part's lifetime.
- Aggregation (empty diamond): shared parts that can exist alone.
- Inheritance: a line with an empty triangle. Realisation: a dashed line with an empty triangle.
- In an interview, show only the important classes and methods.
Common mistakes
- Drawing every getter and setter in a class diagram, which buries the few methods that matter.
- Spending 20 minutes on the diagram and leaving no time to code.
Not true: A good class diagram shows every getter and setter.
In fact: Listing every getter and setter buries the few methods that matter. Show only the important fields, methods and relationships.
In the interview
I start an LLD answer by listing the main entities. Then I draw a class diagram with the key fields, methods and relationships: composition for owned parts, inheritance only for a true 'is-a', and interfaces for anything likely to vary.
Part of Unit 5: Low-level design: OOP and SOLID in the free System Design course.