Class Relationships and Diagrams
Picking good classes is half of a low-level design. The other half is how they connect. Does an Order own its
line items, or just point at them? Does a Playlist delete its songs when it is deleted? Does Checkout keep a
PaymentGateway around, or borrow one for a single call? Each answer changes the code: who creates an object, who
can change it, and when it goes away.
Interviewers read these choices from your class sketch and from your fields. A design where every class holds a reference to every other class is hard to reason about, and a sketch where every arrow means "something" tells the interviewer nothing. This post covers the five relationships you need, what each one looks like in code, and how to draw them quickly on a whiteboard without learning the full UML notation.
💡 The short version: for every arrow you draw, you should be able to say one of five phrases: "uses for a moment" (dependency), "knows about" (association), "has, but doesn't own" (aggregation), "owns" (composition), or "is a / can do" (inheritance and interfaces). If you can't pick one, you don't know the relationship yet.
The Relationships at a Glance
The relationships go from weakest (one object briefly uses another) to strongest (one object is a kind of another).
| Relationship | Plain words | In code | Lifetime |
|---|---|---|---|
| Dependency | uses for a moment | a parameter or a local variable | the call |
| Association | knows about | a field holding a reference to a peer | independent |
| Aggregation | has, but doesn't own | a field holding parts that exist on their own | parts outlive the whole |
| Composition | owns | a field holding parts the whole creates and hides | parts die with the whole |
| Inheritance / implementation | is a / can do | class Car(Vehicle), implements Payable |
not about objects |
The next sections take them one at a time, each with code that gets it wrong and code that gets it right.