Background
Sections
IntroductionRequirements & Problem AnalysisConstraints & AssumptionsEstimation TechniquesFunctional vs Non-Functional RequirementsMoSCoW PrioritizationSystem Design FundamentalsArchitecture DiagramClass DiagramComponent DiagramData Flow Diagram (DFD)ER Diagram (Entity-Relationship Diagram)High Level Design (HLD)Low Level Design (LLD)Sequence DiagramState DiagramUse Case DiagramData StorageDocument StoresFile StorageGraph DatabasesIn-Memory DatabasesKey-Value StoresNewSQLNoSQL DatabasesObject StorageSQL Databases (RDBMS)Time-Series DatabasesWide-Column StoresDatabase ConceptsACID PropertiesCAP TheoremConsistency ModelsIndexingNormalization & DenormalizationReplicationSharding & PartitioningTransactions & Isolation LevelsScalabilityAuto-Scaling & ElasticityConsensus & Leader ElectionLoad BalancingReplication & Read ReplicasSharding & PartitioningVertical vs Horizontal ScalingAvailability & ReliabilityBackup & Data DurabilityCircuit BreakerData ConsistencyDisaster RecoveryFault Tolerance & FailoverGraceful DegradationHigh AvailabilityNetworkingCDNDNSFirewalls & VPNHTTP & HTTPSLoad Balancer & Reverse ProxyTCP/IP & UDPWebSocketsCachingCache InvalidationCache Read/Write PatternsCaching LayersEviction PoliciesRedis vs MemcachedMessaging & CommunicationDead-Letter QueueIdempotencyKafka vs RabbitMQ vs SQSMessage QueuesPub/SubCompute & ServicesAPI GatewayContainers & OrchestrationMonolith vs MicroservicesServerlessService DiscoveryService MeshWeb Server & App ServerAPI DesignAPI Versioning & IdempotencyAuthentication & AuthorizationGraphQLgRPCPaginationRate Limiting & ThrottlingRESTSecurityAuthentication & AuthorizationData PrivacyEncryptionInput Validation & InjectionOAuth2 & JWTSecrets ManagementXSS & CSRFStorage & File SystemsBackup & RetentionBlock vs File vs Object StorageData Lakes & WarehousesDistributed File SystemsEphemeral StorageObservability & MonitoringDistributed TracingHealth ChecksLoggingMetricsSLI, SLO, SLADesign PatternsBulkhead PatternCircuit Breaker PatternCreational PatternsRate Limiter PatternRetry PatternStructural & Behavioral Patterns

Class Diagram

6 min read

In a Nutshell

A class diagram shows the entities in your system, their attributes, their methods, and how they relate to each other. It's the backbone of Low Level Design — the diagram where you demonstrate object-oriented thinking, SOLID principles, and design patterns. While an architecture diagram shows services and infrastructure, a class diagram zooms inside one service and shows how the code is structured. If the interviewer asks you to "design the classes for X," this is the diagram they want.

2D minimalistic class diagram showing three rectangular boxes with three sections each (name, attributes, methods), connected by lines with different endpoints: solid diamond for composition, open diamond for aggregation, and triangle for inheritance

How It Actually Works

Anatomy of a Class Box

┌────────────────────────┐
│     <<interface>>       │  ← stereotype (optional)
│      ClassName          │  ← name
├────────────────────────┤
│ - privateAttr: Type     │  ← attributes
│ + publicAttr: Type      │     - = private
│ # protectedAttr: Type   │     + = public
├────────────────────────┤     # = protected
│ + methodName(): RetType │  ← methods
│ - helperMethod(): void  │
└────────────────────────┘

Relationship Types

Relationship Symbol Meaning Example
Association Solid line "uses" or "knows about" Order ── Customer
Aggregation Open diamond ◇─ "has a" (weak ownership — child can exist alone) Team ◇── Player
Composition Filled diamond ◆─ "owns" (strong ownership — child can't exist without parent) Order ◆── OrderItem
Inheritance Triangle △─ "is a" (child extends parent) Dog △── Animal
Implementation Dashed triangle △- - "implements" (class realizes interface) EmailSender △- - NotificationSender
Dependency Dashed arrow ⟶ "uses temporarily" (method parameter, local variable) OrderService ⟶ PaymentGateway

Multiplicity

Written at each end of a relationship line:

Notation Meaning
1 Exactly one
0..1 Zero or one (optional)
* or 0..* Zero or more
1..* One or more
3..5 Three to five

2D minimalistic diagram showing the six relationship types side by side, each with its symbol, a simple two-box example, and a one-line description

When to Use Class Diagrams

  • LLD interviews — When asked to design the internal structure of a service
  • Design pattern application — Showing how Strategy, Observer, Factory, or Decorator patterns are used
  • API/SDK design — Defining the public interface of a library
  • Domain modeling — Before writing code, to align on entities and their relationships

When NOT to Use Class Diagrams

  • In HLD — use architecture diagrams instead
  • For data persistence — use ER diagrams (they map to tables; class diagrams map to code)
  • For behavior/flow — use sequence or state diagrams

Seeing It in Action

Scenario: Class diagram for a library management system

┌───────────────────────┐       ┌────────────────────────┐
│       Library          │       │    <<interface>>        │
├───────────────────────┤       │    SearchStrategy       │
│ - name: String         │       ├────────────────────────┤
│ - books: List<Book>    │       │ + search(query): Book[]│
├───────────────────────┤       └────────△───────────────┘
│ + addBook(book): void  │               │ implements
│ + searchBooks(): Book[]│       ┌───────┴──────┐
│ + registerMember(): ID │       │              │
└───────────┬───────────┘  ┌────┴─────┐  ┌────┴──────┐
            │ 1         *  │TitleSearch│  │ISBNSearch  │
            ◆              ├──────────┤  ├───────────┤
┌───────────┴───────────┐  │+search() │  │+search()  │
│        Book            │  └──────────┘  └───────────┘
├───────────────────────┤
│ - isbn: String         │
│ - title: String        │          ┌────────────────────┐
│ - author: Author       │          │      Member         │
│ - status: BookStatus   │          ├────────────────────┤
├───────────────────────┤          │ - memberId: String  │
│ + borrow(): boolean    │          │ - name: String      │
│ + return(): void       │          │ - borrowedBooks: [] │
│ + isAvailable(): bool  │          ├────────────────────┤
└───────────────────────┘          │ + borrowBook(): bool│
            △                       │ + returnBook(): void│
            │ extends                └────────────────────┘
  ┌─────────┴─────────┐                      │
  │                    │               borrows │ 0..*
┌─┴──────────┐  ┌─────┴──────┐               │
│ PhysicalBook│  │  EBook      │               ▼
├────────────┤  ├────────────┤         ┌──────────────┐
│ - shelf: Str│  │ - fileUrl   │         │  BorrowRecord │
│ - condition │  │ - format    │         ├──────────────┤
├────────────┤  ├────────────┤         │ - borrowDate  │
│ +getShelf() │  │+download() │         │ - dueDate     │
└────────────┘  └────────────┘         │ - returnDate? │
                                        └──────────────┘

Design decisions visible:

  • Composition (◆): Library owns Books — a book doesn't exist outside a library context
  • Inheritance (△): PhysicalBook and EBook extend Book — shared attributes, different behavior
  • Strategy pattern: SearchStrategy interface with pluggable implementations (TitleSearch, ISBNSearch)
  • Multiplicity: One Library has many (*) Books. One Member has zero or more BorrowRecords.

Interview Questions

  1. Q: What's the difference between aggregation and composition? Give an example of each. Hint: Composition: Order ◆── OrderItem — if the order is deleted, its items are deleted too (strong ownership). Aggregation: Department ◇── Employee — if the department is dissolved, employees still exist (weak ownership). The distinction matters for cascade deletes and lifecycle management.

  2. Q: Design a class diagram for a parking lot system. Hint: Classes: ParkingLot (composition with ParkingFloor), ParkingFloor (composition with ParkingSpot), ParkingSpot (has SpotType enum: COMPACT, REGULAR, LARGE), Vehicle (inheritance: Car, Truck, Motorcycle), Ticket, Payment. Use Strategy for pricing (hourly, daily, flat rate).

  3. Q: How do class diagrams relate to database ER diagrams? Hint: Classes map roughly to tables, attributes to columns, and relationships to foreign keys. But class diagrams include behavior (methods), inheritance (which doesn't map cleanly to relational tables), and in-memory relationships. ER diagrams are purely about persistent data structure.

  4. Q: When would you use an interface vs an abstract class in your class diagram? Hint: Interface: when you want to define a contract that multiple unrelated classes can implement (a Searchable interface for books, members, and transactions). Abstract class: when you want to share code between related classes (Vehicle with shared licensePlate attribute and park() method, extended by Car and Truck).

  5. Q: Your class diagram has a class with 15 methods and 10 attributes. What's wrong, and how do you refactor? Hint: It violates Single Responsibility Principle — it's doing too many things. Break it into smaller classes by responsibility. Use composition: extract groups of related attributes and methods into separate classes (e.g., extract address fields into an Address class, payment logic into a PaymentProcessor class).

References

  • UML Class Diagram — Visual Paradigm — comprehensive notation guide
  • Head First Design Patterns by Freeman & Robson — design patterns illustrated with class diagrams
  • Clean Code by Robert C. Martin — principles for well-structured classes

Dive Deeper