Skip to main content

Class Diagram

Editorial

Purpose of the Class Diagram

The class diagram is the structural blueprint of our Parking Lot system. It answers three fundamental questions:

  1. What classes exist in the system and what data/behavior does each own?
  2. How do classes relate — which owns which? Which inherits from which? Which collaborates with which?
  3. Why is the design structured this way — what requirement drove each design decision?

We'll derive every class directly from the requirements we defined earlier. No class should exist without a requirements-driven justification. This is the class diagram discipline: every box on the whiteboard must trace back to a functional requirement.

For the Parking Lot — an Easy-level problem — we'll end up with 10 classes, 1 interface and 2 enums. That's a manageable number, but each class, each relationship, and each attribute choice will be deliberate.

Identifying Classes from Requirements

Using the noun-verb extraction technique from Fundamentals S8, we analyze our functional requirements to discover candidate classes and methods.

Key Nouns → Candidate Classes:

RequirementNouns FoundCandidate Class
FR1: "The parking lot has multiple floors"parking lot, floorsParkingLot, Floor
FR2: "Each floor has spots of different types"spots, typesParkingSpot, SpotType (enum)
FR3: "Support motorcycles, cars, and trucks"motorcycles, cars, trucksVehicle hierarchy
FR5: "Generate a parking ticket on entry"ticketParkingTicket
FR7: "Support multiple pricing models"pricing modelsPricingStrategy (interface)

Key Verbs → Candidate Methods:

RequirementVerbCandidate Method
FR8: "Find the first available spot"findFloor.findAvailableSpot(VehicleType)
FR5: "Park a vehicle"parkParkingLot.parkVehicle(Vehicle)
FR6: "Unpark a vehicle"unparkParkingLot.unparkVehicle(ticketId)
FR6: "Calculate the parking fee"calculatePricingStrategy.calculateFee(duration)
FR9: "Release the spot"release/unparkParkingSpot.unpark()

This gives us a solid starting point: 6 classes (ParkingLot, Floor, ParkingSpot, Vehicle, ParkingTicket, PricingStrategy), 2 enums (VehicleType, SpotType), and 2-3 concrete subclasses for Vehicle and PricingStrategy.

Defining Classes — Attributes and Methods

Let's define each class with its attributes and methods. Every detail traces to a requirement.

Enums

VehicleType — Represents the three vehicle types (FR3):
Values: MOTORCYCLE, CAR, TRUCK

SpotType — Represents the three spot sizes (FR2):
Values: COMPACT, REGULAR, LARGE

Core Classes

Vehicle (abstract) — Base class for all vehicles (FR3):

  • Attributes: licensePlate: String, type: VehicleType
  • Methods: getType(): VehicleType, getLicensePlate(): String
  • Subclasses: Car, Truck, Motorcycle — each sets its VehicleType in the constructor
  • Why abstract? All vehicles share licensePlate and type, but we may add vehicle-specific behavior in extensions (e.g., electric vehicles needing charging).

ParkingSpot — A single spot on a floor (FR2, FR4, FR8, FR9):

  • Attributes: id: int, spotType: SpotType, isOccupied: boolean, vehicle: Vehicle (null when empty)
  • Methods: park(Vehicle): void, unpark(): Vehicle, canFitVehicle(VehicleType): boolean, isAvailable(): boolean
  • The canFitVehicle method encodes the compatibility rules from FR4. This is the Information Expert principle (GRASP from Fundamentals S7) — the spot knows its own type, so it should decide compatibility.

Floor — A single floor in the lot (FR1, FR8, FR10):

  • Attributes: floorNumber: int, spots: List<ParkingSpot>
  • Methods: findAvailableSpot(VehicleType): ParkingSpot, getAvailableSpotCount(SpotType): int
  • The floor iterates its spots to find one compatible with the given vehicle type. It delegates the compatibility check to ParkingSpot.canFitVehicle().

ParkingTicket — Records a parking session (FR5, FR6):

  • Attributes: ticketId: String, vehicle: Vehicle, spot: ParkingSpot, entryTime: DateTime
  • The ticket is an immutable record linking a vehicle to a spot at a point in time — the session record. It has its own identity (the ticketId the lot looks it up by), so it is not a value object.

ParkingLot — The top-level coordinator (FR1, FR5, FR6, FR8):

  • Attributes: name: String, floors: List<Floor>, pricingStrategy: PricingStrategy, activeTickets: Map<String, ParkingTicket>
  • Methods: addFloor(Floor): void, parkVehicle(Vehicle): ParkingTicket, unparkVehicle(ticketId): float, setPricingStrategy(PricingStrategy): void, getAvailableSpots(VehicleType): int
  • The ParkingLot is the facade — it exposes high-level operations and delegates to Floor, ParkingSpot, PricingStrategy internally.

Strategy Interface

PricingStrategy (interface) — Defines how fees are calculated (FR7):

  • Methods: calculateFee(duration: Duration): float
  • Implementations: HourlyPricing (fee = hours, rounded up to a whole hour, × hourly rate), FlatRatePricing (fixed fee regardless of duration)
  • Why an interface? Because multiple pricing algorithms need to be swappable at runtime without changing ParkingLot. This is the Strategy Pattern (Fundamentals S12).

Defining Relationships

Now let's determine how these classes connect. Each relationship type is chosen deliberately — not randomly.

ParkingLot ◆→ Floor — Composition (1 to 1..*)

Floors are physically part of the parking structure. A floor cannot exist independently — if we destroy the parking lot, all its floors are destroyed too. The floor's lifecycle is entirely owned by the lot. This is the hallmark of Composition: the part's lifecycle is bound to the whole's. (Fundamentals S4)

Floor ◆→ ParkingSpot — Composition (1 to 1..*)

Spots are painted onto a floor — they don't exist outside the floor. If we demolish a floor, all its spots cease to exist. Again, this is Composition: dependent lifecycle. (Fundamentals S4)

ParkingSpot ── Vehicle — Association (0..1)

A spot may reference a vehicle when occupied, but the vehicle exists independently of the spot. When a car leaves, the car continues to exist in the real world — it doesn't get destroyed. This is Association: independent lifecycle, temporary connection. The multiplicity is 0..1 because a spot is either empty (0) or has exactly one vehicle (1). (Fundamentals S4)

ParkingLot ── PricingStrategy — Association

The lot uses a pricing strategy but doesn't own it in a lifecycle sense. The strategy is an injected dependency — it can be swapped at runtime. This is Association (or more precisely, a Strategy dependency). (Fundamentals S4)

Vehicle △ Car, Truck, Motorcycle — Inheritance

Concrete vehicle types extend the abstract Vehicle class. They share the licensePlate attribute and getType() method, while each sets its own VehicleType. This is Inheritance: "is-a" relationship. A Car is-a Vehicle. (Fundamentals S3)

HourlyPricing, FlatRatePricing ⤑ PricingStrategy — Implementation

Concrete pricing strategies implement the PricingStrategy interface. This is Interface Implementation: the dashed line with an open triangle in UML.

Why Composition between ParkingLot → Floor → Spot (not Aggregation)?

This is a common interview question. The answer: floors are structurally bound to the lot. You can't take a floor out of Building A and plug it into Building B. Similarly, spot #42 on Floor 3 is defined by its position on that floor — it doesn't have meaning outside that context. Aggregation would imply the parts can exist independently (like a Professor belonging to a Department — the professor exists even if the department is dissolved). That's not the case here.

Build the Class Diagram

Let's construct the diagram step by step, starting with the core entities and progressively adding relationships and the Strategy Pattern. Build it below the way you would on a whiteboard: place each step's classes, predict how each pair is related, and read the reason behind it — then explore any class, and see why the lot composes its floors instead of aggregating them.

Interactive: the Parking Lot class diagram, built in four steps — the lot, its floors and spots; the vehicles; the Strategy Pattern; the session record. After each step's classes are placed, the learner predicts each relationship the lesson gives a reason for: ParkingLot composes its Floors (1..*) and a Floor its ParkingSpots (1..*) — composition, not aggregation; a ParkingSpot holds 0..1 Vehicle, an association; Car extends the abstract Vehicle; ParkingLot uses a PricingStrategy, an association; HourlyPricing realizes the PricingStrategy interface. Truck, Motorcycle, FlatRatePricing, the enum dependencies and ParkingTicket's links draw themselves. Any class unfolds into its full UML box with its relationships and the lesson's reasons. A last view destroys the usage example's lot: its floors and spots go with it while car1 and the pricing strategy stay — and with aggregation the floors would outlive the lot, which is why the lesson rejects it.

Complete Class Diagram

A UML class diagram of the parking lot system. Top row, left to right: ParkingLot (name, floors, pricingStrategy, activeTickets — a map from ticket id to ParkingTicket; addFloor(floor), parkVehicle(vehicle) returning a ParkingTicket, unparkVehicle(ticketId) returning the fee, setPricingStrategy(strategy), getAvailableSpots(type)) composes one or more Floors (floorNumber, spots; findAvailableSpot(type) returning a ParkingSpot, getAvailableSpotCount(type)), and each Floor composes one or more ParkingSpots (id, spotType, isOccupied, vehicle; park(vehicle), unpark() returning the Vehicle, canFitVehicle(type), isAvailable()), labelled "has"; the spot depends on the SpotType enumeration (COMPACT, REGULAR, LARGE). Middle row: under the lot, the PricingStrategy interface (calculateFee(duration) returning a float), which the lot "uses"; under the floor, ParkingTicket (ticketId, vehicle, spot, entryTime), associated with exactly one ParkingSpot and one Vehicle; under the spot, the abstract class Vehicle (licensePlate, type; getType(), getLicensePlate()), which a spot "holds" zero or one of, and which depends on the VehicleType enumeration (MOTORCYCLE, CAR, TRUCK). Bottom row: HourlyPricing (hourlyRate) and FlatRatePricing (flatRate) realize PricingStrategy through one shared triangle, each with calculateFee(duration); Car, Truck and Motorcycle extend Vehicle through one shared triangle. A legend explains composition, association, dependency, realization and generalization, and the colours: the lot's structure, pricing (Strategy), vehicles, the parking session and the enumerations.

Key Design Decisions

Every design choice has a rationale. Here are the key decisions an interviewer would ask about:

1. Why Composition (not Aggregation) for ParkingLot → Floor → ParkingSpot?

Floors are physically constructed within the parking structure — they don't exist independently. You can't detach Floor 3 from Parking Lot A and reinstall it in Parking Lot B. Similarly, Spot #42 on Floor 3 is defined by its physical position — remove the floor, and the spots cease to exist. This dependent lifecycle is the defining characteristic of Composition. Aggregation would imply the parts survive the destruction of the whole, which isn't true here. (Fundamentals S4)

2. Why an Abstract Class for Vehicle (not an Interface)?

All vehicle types share the licensePlate attribute and type field. An abstract class lets us define this shared state once and inherit it. A Java interface can't hold instance fields (Python is more flexible, but we design language-agnostically). If vehicles only shared behavior (methods with no shared state), an interface would be appropriate. (Fundamentals S4)

3. Why Strategy Pattern for Pricing (not if-else)?

Without Strategy, adding a new pricing model (say, DynamicSurgePricing) requires adding another branch to a conditional inside ParkingLot — violating the Open/Closed Principle (Fundamentals S6). With Strategy, we create a new class implementing PricingStrategy and inject it. The ParkingLot never changes. This is a textbook application of OCP. (Fundamentals S12)

4. Why does ParkingSpot own the compatibility logic?

We put canFitVehicle(VehicleType) on ParkingSpot rather than on Floor or ParkingLot. This follows the Information Expert principle from GRASP (Fundamentals S7) — assign responsibility to the class that has the information needed to fulfill it. The spot knows its own spotType, so it should decide whether a given vehicle type fits.

5. Why ParkingTicket as a separate class?

The ticket represents a session — a time-bounded relationship between a vehicle, a spot, and the parking lot. It's not a property of the vehicle (a vehicle doesn't always have a ticket) or the spot (a spot doesn't always have a session). It's an association class that captures the parking event. Creating it as a separate class follows SRP — the ticket manages session data, not vehicle data or spot data.