SyntaxPilot
Courses/Low-Level Design/Lesson 59
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 59 of 90

Design a parking lot 1: requirements and model

parking lot requirementsParkingLotParkingFloorParkingSpotspot typesVehicle hierarchyTicketEntryGateExitGateDisplayBoardclass diagramsingleton parking lot debate

These are the notes for Low-Level Design (LLD) episode 59. We warmed up with Tic-Tac-Toe (episode 57) and Snake and Ladder (episode 58). Now comes the most famous machine-coding problem of them all: the parking lot. It is big, so it gets two episodes. This one, part 1, covers the requirements (what we must build, and what we leave out) and the model (the classes and how they connect): spot types, the Vehicle hierarchy, ParkingLot, ParkingFloor and ParkingSpot, the Ticket, the EntryGate and ExitGate, a DisplayBoard that never lies, the full class diagram, and the singleton parking lot debate. Part 2 (episode 60) adds smarter spot allocation, pricing, payment and two gates working at the same moment.

We follow the course's "you invent it" order: a real-life problem, the obvious code, watching it fail with real output, asking why, and then inventing the fix.

How the code was run: every program was saved as Main.java in an empty folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output, error message and stack trace below is exactly what was printed. The mall, its floors and its number plates are made up.

1. The problem (the brief)

"Design a parking lot." That is often the whole brief in an interview. A machine-coding round is an interview round where you design and code a small, working system in about 60 to 120 minutes (episodes 55 and 56). The brief is deliberately vague, because the interviewer wants to see you turn it into clear requirements before you write any code.

A requirement is one thing the system must do, or one quality it must have, written down so everyone agrees on it. "A truck must never be given a bike spot" is a requirement.

2. The real-life idea: Saturday at the mall basement

It's Saturday at a busy mall. In the basement, the attendant, Ramesh, runs the parking with two tools: a notebook listing the spots, and a chalk board at the entrance that shows how many spots are free.

  1. A truck takes a bike spot. A truck arrives. The notebook says spot 1 is free, so the truck goes to spot 1. But spot 1 is a tiny bike spot. The notebook had no idea that spots come in sizes.
  2. The board says 2 free. A bike leaves. Ramesh writes it in the notebook, but forgets to update the chalk board. The board says 2 free; the real number is 3.
  3. The mall grows. Now there are 3 floors, 300 spots, gates at both ends and a queue of cars outside. A notebook won't do. It has to be a system.

Every part of the basement becomes part of the design:

In the mall basement In the design
The building and its basement levels ParkingLot, which holds a list of ParkingFloors
A painted, numbered bay, sized for a bike, a car or a truck ParkingSpot, with an id and a SpotType (SMALL, COMPACT, LARGE)
Bikes, cars and trucks: different sizes, but all vehicles The Vehicle hierarchy: an abstract Vehicle with Bike, Car, Truck
The paper slip you get at the barrier Ticket: who parked, in which spot, and when
The boom barrier at the way in EntryGate: find a spot, take it, issue a ticket
The boom barrier at the way out ExitGate: take the ticket back, free the spot
Ramesh's chalk board DisplayBoard, which counts free spots from the spots themselves
Ramesh's notebook Replaced: the spots themselves remember what is parked in them

3. The obvious way, and how it breaks

The notebook, written as code. An array of four strings is the notebook: spots 0 and 1 are bike-sized, spots 2 and 3 are car-sized, and null (Java's "nothing here" value) means free. An int called free is the chalk board.

import java.util.Arrays;
public class Main {
    static String[] spots = new String[4];         // spots 0-1 are bike-sized, 2-3 car-sized; null = free
    static int free = 4;                           // the number on the display board
    static int park(String vehicle) {
        for (int i = 0; i < spots.length; i++)
            if (spots[i] == null) { spots[i] = vehicle; free--; return i; }
        return -1;
    }
    static void leave(int spot) { spots[spot] = null; }
    public static void main(String[] args) {
        System.out.println("bike KA01  -> spot " + park("bike KA01"));
        System.out.println("truck MH12 -> spot " + park("truck MH12"));
        leave(0);                                  // the bike goes home
        System.out.println("Display board: " + free + " free");
        System.out.println("Spots: " + Arrays.toString(spots));
    }
}

park takes the first null spot and decreases free. leave sets the spot back to null. main parks a bike, then a truck, then the bike leaves. Arrays.toString prints an array as [a, b, c].

Output:

bike KA01  -> spot 0
truck MH12 -> spot 1
Display board: 2 free
Spots: [null, truck MH12, null, null]

Two bugs, both exactly like Ramesh's:

  • The truck got spot 1, a bike-sized spot. Nothing in the code knows sizes.
  • The board says 2 free, but the spots line shows three nulls: 3 free. leave forgot to update the counter.

Why it failed

  1. A spot is just a slot in an array, with no size and no type.
  2. A vehicle is just a string, with no type either. So nothing can say "a truck doesn't fit here".
  3. The free count is a second copy of the truth. The spots already know which are free; free is a copy that someone must keep in step by hand. Copies drift apart.
  4. There is no ticket. Nobody can prove who parked where, or when.

In a machine-coding round the fix starts before any code: write the requirements, then turn the nouns into classes (noun analysis, episode 20).

4. Parking lot requirements

Parking lot requirements are the written list of what our parking lot must do and how well it must do it, agreed with the interviewer before coding. They come in two kinds.

4.1 Functional requirements: what it must DO

A functional requirement describes a behaviour: an action the system performs or a rule it enforces. You can test it with "given this, the system does that".

# Functional requirement Example
F1 The lot has several floors; each floor has many spots Floor 0 has spots F0-1, F0-2, ...
F2 Each spot has a type: SMALL, COMPACT or LARGE F0-1 is SMALL (a bike bay)
F3 Vehicles are bikes, cars and trucks; each needs a spot it fits in A truck needs a LARGE spot
F4 A smaller vehicle may use a bigger spot, never the other way round A bike may use a LARGE spot
F5 Entry gate: find a free spot that fits, take it, issue a ticket (spot + entry time) Car KA01 gets ticket 1 for F0-2 at 10:00
F6 If no spot fits, the entry gate refuses the vehicle "lot full" for a truck when no LARGE spot is free
F7 Exit gate: take the ticket back and free exactly that spot (paying is part 2) Ticket 1 frees F0-2
F8 Display board: free spots on each floor, for each type floor 0: SMALL 1 COMPACT 0 LARGE 0

4.2 Non-functional requirements: how WELL it must work

A non-functional requirement describes a quality, not a behaviour: speed, correctness under load, how easy it is to change. It doesn't add a feature; it limits how the features may be built.

# Non-functional requirement What it means for the design
N1 Fast spot search With 300 spots, the gate must not keep a queue waiting. Part 1 uses a simple scan; part 2 makes it faster
N2 Correct with two gates at once Two gates must never hand the same spot to two cars (this is a concurrency problem: several things running at the same time; part 2)
N3 Easy to extend Adding electric spots or a new vehicle type should change one place, not ten
N4 The board is always right The free count must never drift from the real spots (Ramesh's bug)

4.3 Clarifying questions

A clarifying question is a question you ask the interviewer to remove a doubt in the brief. Asking them shows you think before you type, and every answer becomes an assumption you write down.

Question Our assumption
How many floors and spots? Any number; set when the lot is built
Which vehicle types? Bike, car, truck (more may come later)
Can a bike use a car spot? Yes: a smaller vehicle fits a bigger spot, never the reverse
How many entry and exit gates? Several; they all share one lot
Electric charging spots, reserved or accessible spots? Not now, but keep room for them (the mini project adds electric spots)
Pricing and payment? Part 2
What does a ticket hold? An id, the vehicle, the spot and the entry time
What does the display board show? Free spots per floor, per spot type
Is there a user interface? No: a console demo with a main method

4.4 Scope and out of scope

Scope is the part of the problem you agree to build now. Out of scope is what you agree to leave out, said out loud so the interviewer knows you saw it.

  • In scope today: the model (all classes), parking a vehicle, exiting, and the display board.
  • Part 2 (episode 60): smarter allocation, pricing and payment, the ticket's life from entry to exit, two gates at the same time.
  • Out of scope: a database, a web or mobile app, number-plate cameras, monthly passes, staff accounts. Each of these would sit around the model, not change it.

5. Entities by noun analysis

Noun analysis (episode 20) means reading the requirements and underlining the nouns: each noun is a candidate entity, a thing the system must remember or act as, which usually becomes a class.

From section 4: lot, floor, spot, spot type, vehicle (bike, car, truck), ticket, entry gate, exit gate, display board, entry time.

  • ParkingLot: the whole building. It holds the floors and answers "is there a free spot that fits this vehicle?"
  • ParkingFloor: one level. It holds its spots and can find a free fitting spot on that level.
  • ParkingSpot: one painted bay. It has an id like F0-2, a type, and the vehicle parked in it (or nothing).
  • Spot types: the fixed list of spot sizes, SMALL, COMPACT and LARGE, written as an enum SpotType.
  • Vehicle hierarchy: an abstract Vehicle with Bike, Car and Truck below it.
  • Ticket: the proof of parking: id, vehicle, spot, entry time.
  • EntryGate: finds a spot, takes it, issues a ticket.
  • ExitGate: takes a ticket and frees that spot.
  • DisplayBoard: shows free spots per floor and type, counted live.

"Entry time" is a noun too, but it is only a value inside a ticket, not a thing with its own behaviour, so it becomes a field, not a class.

6. Spot types and the Vehicle hierarchy

6.1 Enums: a fixed list of values

An enum (short for enumeration) is a type with a fixed list of named values. enum SpotType { SMALL, COMPACT, LARGE } means a spot type can only ever be one of those three; SpotType.HUGE would not compile. We also add enum VehicleType { BIKE, CAR, TRUCK }.

Enums in Java can have methods, like classes. Every enum value also knows its position in the list: ordinal() returns it (SMALL.ordinal() is 0, COMPACT is 1, LARGE is 2).

6.2 The fit rule

We list the spot types from smallest to largest. A bike needs at least SMALL, a car at least COMPACT, a truck at least LARGE. So the fit rule is one comparison:

A spot fits a vehicle if the spot's size is at least the size the vehicle needs.

compareTo compares two values and returns a negative number if the first is smaller, 0 if equal, and a positive number if bigger. For an enum, "smaller" means "declared earlier in the list". So LARGE.compareTo(COMPACT) is positive, and SMALL.compareTo(LARGE) is negative. That is why the declaration order matters.

Vehicle Needs at least SMALL COMPACT LARGE
Bike SMALL fits fits fits
Car COMPACT no fits fits
Truck LARGE no no fits

6.3 Abstract class: the Vehicle hierarchy

A class hierarchy is a family of classes where general classes sit on top and more specific ones extend them. The class being extended is the superclass (parent); the extending one is the subclass (child), which inherits the parent's fields and methods (inheritance).

An abstract class is a class you cannot create objects of directly; it exists to be extended. It can hold shared code (here, the number plate) and declare abstract methods: methods with no body that every non-abstract subclass must fill in (override). Vehicle declares abstract VehicleType type();, and Bike, Car and Truck each return their own type.

6.4 Spots that refuse a misfit

neededBy maps each vehicle to the smallest spot it needs, with a switch expression: a switch that produces a value, written switch (v) { case BIKE -> SMALL; ... }. Each case X -> value gives the result for one input. For an enum, the compiler checks that every value is covered; that is called being exhaustive.

enum VehicleType { BIKE, CAR, TRUCK }
enum SpotType { SMALL, COMPACT, LARGE;                            // ordered from smallest to largest
    static SpotType neededBy(VehicleType v) {                     // the smallest spot each vehicle needs
        return switch (v) { case BIKE -> SMALL; case CAR -> COMPACT; case TRUCK -> LARGE; }; }
    boolean fits(VehicleType v) { return compareTo(neededBy(v)) >= 0; }   // same size or bigger
}
abstract class Vehicle {                                          // the Vehicle hierarchy
    private final String plate;
    Vehicle(String plate) { this.plate = plate; }
    abstract VehicleType type();
    public String toString() { return type() + " " + plate; }
}
class Bike extends Vehicle { Bike(String p) { super(p); } VehicleType type() { return VehicleType.BIKE; } }
class Car extends Vehicle { Car(String p) { super(p); } VehicleType type() { return VehicleType.CAR; } }
class Truck extends Vehicle { Truck(String p) { super(p); } VehicleType type() { return VehicleType.TRUCK; } }
class ParkingSpot { final String id; final SpotType type; private Vehicle parked;  // null = free
    ParkingSpot(String id, SpotType type) { this.id = id; this.type = type; }
    boolean isFree() { return parked == null; }
    void park(Vehicle v) {
        if (!isFree()) throw new IllegalStateException(id + " is taken by " + parked);
        if (!type.fits(v.type())) throw new IllegalArgumentException(v + " does not fit " + type + " spot " + id);
        parked = v;
    } }
public class Main { public static void main(String[] args) {
    ParkingSpot big = new ParkingSpot("F0-L1", SpotType.LARGE), small = new ParkingSpot("F0-S1", SpotType.SMALL);
    big.park(new Bike("KA01"));  System.out.println("bike in a LARGE spot: ok");
    small.park(new Truck("MH12"));
}}

Output:

bike in a LARGE spot: ok
Exception in thread "main" java.lang.IllegalArgumentException: TRUCK MH12 does not fit SMALL spot F0-S1
    at ParkingSpot.park(Main.java:21)
    at Main.main(Main.java:27)

Reading the code:

  • private final String plate: private means only code inside Vehicle can touch it; final means it is set once, in the constructor, and never changes. Hiding data behind methods like this is encapsulation.
  • super(p) calls the parent (Vehicle) constructor, which stores the plate.
  • toString() is the method Java calls when an object is turned into text, so a truck prints as TRUCK MH12.
  • ParkingSpot keeps the parked vehicle, or null when free. park guards two rules: a taken spot throws IllegalStateException (the object is not in a state that allows this call), and a misfit throws IllegalArgumentException (the argument is wrong for this method).
  • An exception is Java's way of stopping normal flow because something should not happen. Uncaught, it prints its message and a stack trace: the chain of method calls that led there, with line numbers (ParkingSpot.park at line 21, called from main at line 27).

The bike in the large spot is fine (F4). The truck in the small spot is refused with our own message. The spot owns the fit rule, so no notebook, gate or careless caller can ever put a truck in a bike bay again.

The other rule works too. With the same classes and this main:

public class Main { public static void main(String[] args) {
    ParkingSpot big = new ParkingSpot("F0-L1", SpotType.LARGE);
    big.park(new Bike("KA01"));
    big.park(new Car("KA02"));                                     // the same spot again
}}

Output:

Exception in thread "main" java.lang.IllegalStateException: F0-L1 is taken by BIKE KA01
    at ParkingSpot.park(Main.java:20)
    at Main.main(Main.java:27)

6.5 The debate: subclasses, or one Vehicle class with a type field?

The video promised both sides. There are two common ways to model vehicles:

  • Option A, a hierarchy: abstract class Vehicle with subclasses Bike, Car, Truck (what section 6.4 does).
  • Option B, one class with a type field: a single Vehicle that stores a VehicleType value, such as record Vehicle(String plate, VehicleType type). A type field is a field whose value says what kind of thing the object is. (The folded code in sections 7 and 8 uses this option, to keep the screen short.)

A record is a short class whose only job is to carry values. You list the fields in brackets; Java writes the constructor, the getter methods (plate(), type()), equals, hashCode and a toString like Vehicle[plate=KA01, type=CAR] for you. Record fields are final.

Both side by side, run for real:

enum SpotType { SMALL, COMPACT, LARGE }

// Option A: a Vehicle hierarchy. Each subclass fills in its own rule.
abstract class Vehicle {
    final String plate;
    Vehicle(String plate) { this.plate = plate; }
    abstract SpotType needs();
    public String toString() { return getClass().getSimpleName() + " " + plate + " needs " + needs(); }
}
class Bike extends Vehicle { Bike(String p) { super(p); } SpotType needs() { return SpotType.SMALL; } }
class Car extends Vehicle { Car(String p) { super(p); } SpotType needs() { return SpotType.COMPACT; } }
class Truck extends Vehicle {
    final double lengthM;                                  // data only a truck has
    Truck(String p, double lengthM) { super(p); this.lengthM = lengthM; }
    SpotType needs() { return SpotType.LARGE; }
}

// Option B: one class with a type field. The rule lives in the enum.
enum VehicleType { BIKE, CAR, TRUCK;
    SpotType needs() { return switch (this) { case BIKE -> SpotType.SMALL; case CAR -> SpotType.COMPACT; case TRUCK -> SpotType.LARGE; }; }
}
record PlainVehicle(String plate, VehicleType type) {
    public String toString() { return type + " " + plate + " needs " + type.needs(); }
}

public class Main {
    public static void main(String[] args) {
        Vehicle[] a = { new Bike("KA01"), new Car("KA02"), new Truck("MH12", 7.5) };
        for (Vehicle v : a) System.out.println("A: " + v);
        PlainVehicle[] b = { new PlainVehicle("KA01", VehicleType.BIKE), new PlainVehicle("KA02", VehicleType.CAR),
                             new PlainVehicle("MH12", VehicleType.TRUCK) };
        for (PlainVehicle v : b) System.out.println("B: " + v);
    }
}

Output:

A: Bike KA01 needs SMALL
A: Car KA02 needs COMPACT
A: Truck MH12 needs LARGE
B: BIKE KA01 needs SMALL
B: CAR KA02 needs COMPACT
B: TRUCK MH12 needs LARGE

(getClass().getSimpleName() gives the class name, like Truck.)

Option A: subclasses Option B: one class + type field
Pros Each kind can have its own data (Truck.lengthM) and own behaviour, by overriding methods Very little code: one record and one enum
Adding a kind = adding a class; the compiler forces it to implement every abstract method All the rules about kinds sit together in the enum, easy to read
Matches how interviewers draw the class diagram Easy to store in a database or read from input (VehicleType.valueOf("CAR"))
Cons More classes that may differ only by one returned value Kind-specific data has nowhere natural to live (a truck's length on every bike?)
Many tiny subclasses can feel like ceremony Kind-specific behaviour turns into switch/if (type == TRUCK) in many places
A vehicle cannot change its kind after creation Every new kind means checking each of those switches (exhaustive switches help: the compiler finds them)

Rule of thumb. If the kinds differ only in data (a size), a type field is enough and simpler. If they differ in behaviour or carry different fields, use subclasses. In an interview, draw the hierarchy (it is what the interviewer expects to see), say out loud that a type field would also work here because the kinds differ mostly by size, and explain when you'd switch.

Expert note: sealed classes. Java 17 added sealed classes: a sealed class lists exactly which subclasses are allowed (permits). Then a pattern-matching switch (a switch that checks an object's class, case Truck t ->) is exhaustive over the subclasses, just like a switch over an enum. You get Option A's separate classes with Option B's "the compiler finds every switch" safety:

enum SpotType { SMALL, COMPACT, LARGE }
sealed abstract class Vehicle permits Bike, Car, Truck {
    final String plate;
    Vehicle(String plate) { this.plate = plate; }
}
final class Bike extends Vehicle { Bike(String p) { super(p); } }
final class Car extends Vehicle { Car(String p) { super(p); } }
final class Truck extends Vehicle { Truck(String p) { super(p); } }
public class Main {
    static SpotType needs(Vehicle v) {
        return switch (v) {                                  // pattern switch: the compiler knows all three
            case Bike b  -> SpotType.SMALL;
            case Car c   -> SpotType.COMPACT;
            case Truck t -> SpotType.LARGE;
        };
    }
    public static void main(String[] args) {
        System.out.println(needs(new Truck("MH12")) + " " + needs(new Bike("KA01")));
    }
}

Output:

LARGE SMALL

(A final class cannot be extended further.)

7. ParkingFloor and ParkingLot: first fit, floor by floor

The types from section 6 are folded at the top of the next program: squeezed into four lines so the new code fits on screen. The folded version uses Option B (record Vehicle(String plate, VehicleType type)) and a shorter fit rule based on ordinal(); section 7.2 explains why that shortcut is fragile.

New ideas in this program:

  • List<ParkingSpot> is an ordered list of spots; ArrayList is the usual growable list. List.of(a, b) makes a fixed (unchangeable) list.
  • SpotType... types is a varargs parameter ("variable number of arguments"): the caller can pass any number of spot types, and the method sees them as an array.
  • Optional<ParkingSpot> is a box that holds either one spot or nothing. Optional.of(s) is a full box, Optional.empty() an empty one. It replaces returning null (or -1, like the notebook code), so the caller is forced to handle "no spot". isPresent() asks whether it is full; ifPresent(...) runs code only if it is full; map(...) transforms the value if present; orElse(x) gives the value or x if empty.
  • var lets Java work out a local variable's type from the right-hand side: var spot = lot.findSpot(...) makes spot an Optional<ParkingSpot>. The type is still fixed; you just don't write it.
  • s -> s.parked = v is a lambda: a small unnamed function you can pass to a method. s -> s.id means "given s, return s.id".
  • VehicleType.valueOf("CAR") turns the text "CAR" into the enum value CAR.
import java.util.*;        // VehicleType, SpotType, Vehicle, ParkingSpot: as before, folded up (the sizes line up)
enum VehicleType { BIKE, CAR, TRUCK }   record Vehicle(String plate, VehicleType type) {}
enum SpotType { SMALL, COMPACT, LARGE; boolean fits(VehicleType v) { return ordinal() >= v.ordinal(); } }
class ParkingSpot { final String id; final SpotType type; Vehicle parked;   public String toString() { return id; }
    ParkingSpot(String id, SpotType type) { this.id = id; this.type = type; } }          // parked == null: free
class ParkingFloor {
    final int number;  final List<ParkingSpot> spots = new ArrayList<>();
    ParkingFloor(int number, SpotType... types) {  this.number = number;      // spot id F1-2 = floor 1, spot 2
        for (SpotType t : types) spots.add(new ParkingSpot("F" + number + "-" + (spots.size() + 1), t));
    }
    Optional<ParkingSpot> findSpot(VehicleType v) {                    // first free spot that fits
        for (ParkingSpot s : spots) if (s.parked == null && s.type.fits(v)) return Optional.of(s);
        return Optional.empty();
    }
}
record ParkingLot(List<ParkingFloor> floors) {
    Optional<ParkingSpot> findSpot(VehicleType v) {                    // ask floor 0, then floor 1, ...
        for (ParkingFloor f : floors) { Optional<ParkingSpot> s = f.findSpot(v); if (s.isPresent()) return s; }
        return Optional.empty(); } }
public class Main { public static void main(String[] args) {
    ParkingLot lot = new ParkingLot(List.of(new ParkingFloor(0, SpotType.SMALL, SpotType.COMPACT),
                                            new ParkingFloor(1, SpotType.COMPACT, SpotType.LARGE)));
    for (String name : "CAR CAR TRUCK BIKE CAR".split(" ")) {             // five vehicles arrive
        Vehicle v = new Vehicle("demo", VehicleType.valueOf(name));  var spot = lot.findSpot(v.type());
        spot.ifPresent(s -> s.parked = v);                                 // take the spot
        System.out.println(v.type() + " -> " + spot.map(s -> s.id).orElse("no spot"));
    }
}}

Output:

CAR -> F0-2
CAR -> F1-1
TRUCK -> F1-2
BIKE -> F0-1
CAR -> no spot

7.1 What happened

  • A ParkingFloor builds its spots from the list of types: floor 0 gets F0-1 (SMALL) and F0-2 (COMPACT); floor 1 gets F1-1 (COMPACT) and F1-2 (LARGE).
  • First fit means: walk the spots in order and take the first free one that fits. ParkingLot.findSpot asks floor 0 first, then floor 1.
  • Car 1: F0-1 is SMALL, too small; F0-2 fits. Car 2: floor 0 has nothing that fits, so F1-1. The truck: F1-2, the only LARGE. The bike: F0-1. Car 3: every spot is taken, so the box is empty and we print no spot.

Every vehicle went to a spot that fits, floor by floor. (Here ParkingLot is a record: it only carries its list of floors, plus one method. Records may have methods.)

7.2 Why ordinal() fits works here, and why it is fragile

The folded rule is ordinal() >= v.ordinal(): "the spot's position is at least the vehicle's position". It only works because the two enums happen to line up: BIKE/SMALL are both 0, CAR/COMPACT both 1, TRUCK/LARGE both 2. The comment says it: "the sizes line up". The rule secretly depends on the order of VehicleType, which has nothing to do with sizes.

Now someone adds a scooter in the middle of VehicleType (an innocent-looking change):

enum VehicleType { BIKE, SCOOTER, CAR, TRUCK }          // someone adds SCOOTER in the middle
enum SpotType { SMALL, COMPACT, LARGE;
    boolean fits(VehicleType v) { return ordinal() >= v.ordinal(); } }   // the folded rule
public class Main {
    public static void main(String[] args) {
        for (VehicleType v : VehicleType.values()) {
            StringBuilder s = new StringBuilder(v + " fits:");
            for (SpotType t : SpotType.values()) if (t.fits(v)) s.append(" ").append(t);
            System.out.println(s);
        }
    }
}

(values() returns every enum value in declared order; a StringBuilder builds up text piece by piece with append.)

Output:

BIKE fits: SMALL COMPACT LARGE
SCOOTER fits: COMPACT LARGE
CAR fits: LARGE
TRUCK fits:

It compiles, runs, and is silently wrong: a car no longer fits a compact spot, and a truck fits nothing at all. No error points to the bug.

The safer version is the one from section 6.4: an explicit neededBy map, and compareTo only between spot types (whose order really is "smallest to largest"). Make the same change there:

enum VehicleType { BIKE, SCOOTER, CAR, TRUCK }
enum SpotType { SMALL, COMPACT, LARGE;                         // ordered from smallest to largest
    static SpotType neededBy(VehicleType v) {                  // the smallest spot each vehicle needs
        return switch (v) { case BIKE -> SMALL; case CAR -> COMPACT; case TRUCK -> LARGE; }; }
    boolean fits(VehicleType v) { return compareTo(neededBy(v)) >= 0; }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(SpotType.SMALL.fits(VehicleType.SCOOTER));
    }
}

Output (a compile error, found by javac before the program can run):

Main.java:4: error: the switch expression does not cover all possible input values
        return switch (v) { case BIKE -> SMALL; case CAR -> COMPACT; case TRUCK -> LARGE; }; }
               ^
1 error

The exhaustive switch forces you to decide what a scooter needs. Add case BIKE, SCOOTER -> SMALL (one case can list several values) and every type is right:

enum VehicleType { BIKE, SCOOTER, CAR, TRUCK }
enum SpotType { SMALL, COMPACT, LARGE;                         // ordered from smallest to largest
    static SpotType neededBy(VehicleType v) {                  // the smallest spot each vehicle needs
        return switch (v) { case BIKE, SCOOTER -> SMALL; case CAR -> COMPACT; case TRUCK -> LARGE; }; }
    boolean fits(VehicleType v) { return compareTo(neededBy(v)) >= 0; }
}
public class Main {
    public static void main(String[] args) {
        for (VehicleType v : VehicleType.values()) {
            StringBuilder s = new StringBuilder(v + " fits:");
            for (SpotType t : SpotType.values()) if (t.fits(v)) s.append(" ").append(t);
            System.out.println(s);
        }
    }
}

Output:

BIKE fits: SMALL COMPACT LARGE
SCOOTER fits: SMALL COMPACT LARGE
CAR fits: COMPACT LARGE
TRUCK fits: LARGE

The lesson: never let a rule depend on an enum's order unless that order is the meaning. SpotType's order means size, so compareTo on spot types is fine. VehicleType's order means nothing, so comparing its ordinal() with a spot's is a hidden coupling. Even for SpotType, write a comment ("ordered from smallest to largest") so nobody inserts a value in the wrong place.

8. Ticket, EntryGate, ExitGate and a DisplayBoard that never lies

  • A Ticket holds an id, the vehicle, the spot, and the entry time. It is the proof of parking. It is a record: once issued, it never changes.
  • The EntryGate finds a spot, takes it, and creates the ticket with the next id.
  • The ExitGate takes a ticket and frees exactly that spot. No searching the floors for a plate: the ticket already knows the spot.
  • The DisplayBoard keeps no count of its own. Each time it shows, it counts the free spots from the spots themselves.

That last point is the cure for Ramesh's chalk board. It is called a single source of truth: each fact is stored in exactly one place, and everything else reads it from there. "Is F0-2 free?" is stored only in the spot. The board's number is a derived value, worked out from the source each time, so there is nothing to forget to update.

New ideas in this program:

  • A stream is a pipeline that processes the items of a collection step by step. spots.stream().filter(...).count() means: take the spots, keep only those matching the condition, count them. flatMap(f -> f.spots.stream()) turns "a stream of floors" into "one stream of all their spots". findFirst() gives the first item as an Optional.
  • orElseThrow(() -> new IllegalStateException(...)) returns the value inside the Optional, or throws the given exception if it is empty.
  • nextId++ uses the current value, then adds 1.
import java.util.*;        // VehicleType, SpotType, Vehicle, ParkingSpot: as before, folded up (the sizes line up)
enum VehicleType { BIKE, CAR, TRUCK }   record Vehicle(String plate, VehicleType type) {}
enum SpotType { SMALL, COMPACT, LARGE; boolean fits(VehicleType v) { return ordinal() >= v.ordinal(); } }
class ParkingSpot { final String id; final SpotType type; Vehicle parked;   public String toString() { return id; }
    ParkingSpot(String id, SpotType type) { this.id = id; this.type = type; } }          // parked == null: free
class ParkingFloor { final int number; final List<ParkingSpot> spots = new ArrayList<>();       // as before
    ParkingFloor(int number, SpotType... types) { this.number = number;
        for (SpotType t : types) spots.add(new ParkingSpot("F" + number + "-" + (spots.size() + 1), t)); }
    long free(SpotType t) { return spots.stream().filter(s -> s.parked == null && s.type == t).count(); } }
record ParkingLot(List<ParkingFloor> floors) { Optional<ParkingSpot> findSpot(VehicleType v) { return floors
    .stream().flatMap(f -> f.spots.stream()).filter(s -> s.parked == null && s.type.fits(v)).findFirst(); } }
record Ticket(int id, Vehicle vehicle, ParkingSpot spot, String entryTime) {}   // proof: who parked where, when
class EntryGate { final ParkingLot lot; int nextId = 1;   EntryGate(ParkingLot lot) { this.lot = lot; }
    Ticket enter(Vehicle v, String time) {                                 // find a spot, take it, print a ticket
        ParkingSpot s = lot.findSpot(v.type()).orElseThrow(() -> new IllegalStateException("lot full: " + v));
        s.parked = v;  return new Ticket(nextId++, v, s, time); } }
class ExitGate { Vehicle exit(Ticket t) { Vehicle v = t.spot().parked; t.spot().parked = null; return v; } }
class DisplayBoard { void show(ParkingLot lot) { for (ParkingFloor f : lot.floors()) {     // counted live
    String s = "floor " + f.number + ":";  for (SpotType t : SpotType.values()) s += " " + t + " " + f.free(t);
    System.out.println(s); } } }
public class Main { public static void main(String[] args) {
    var lot = new ParkingLot(List.of(new ParkingFloor(0, SpotType.SMALL, SpotType.COMPACT),
                                     new ParkingFloor(1, SpotType.LARGE)));
    var entry = new EntryGate(lot); var exit = new ExitGate(); var board = new DisplayBoard();
    Ticket t1 = entry.enter(new Vehicle("KA01", VehicleType.CAR), "10:00");   System.out.println(t1);
    entry.enter(new Vehicle("MH12", VehicleType.TRUCK), "10:05");   board.show(lot);
    System.out.println("exit: " + exit.exit(t1).plate());   board.show(lot);
    entry.enter(new Vehicle("DL05", VehicleType.TRUCK), "10:10");  }}

Output:

Ticket[id=1, vehicle=Vehicle[plate=KA01, type=CAR], spot=F0-2, entryTime=10:00]
floor 0: SMALL 1 COMPACT 0 LARGE 0
floor 1: SMALL 0 COMPACT 0 LARGE 0
exit: KA01
floor 0: SMALL 1 COMPACT 1 LARGE 0
floor 1: SMALL 0 COMPACT 0 LARGE 0
Exception in thread "main" java.lang.IllegalStateException: lot full: Vehicle[plate=DL05, type=TRUCK]
    at EntryGate.lambda$enter$0(Main.java:15)
    at java.base/java.util.Optional.orElseThrow(Optional.java:403)
    at EntryGate.enter(Main.java:15)
    at Main.main(Main.java:28)

Reading the output:

  • The ticket: id 1, the car, spot F0-2, entry time 10:00. (The record wrote that toString for us; the spot prints as its id because ParkingSpot.toString returns id.)
  • The board after the truck: floor 0 has one SMALL free; floor 1 has nothing free, the truck is in its only spot.
  • After the car exits, floor 0 shows one COMPACT free again, without anyone updating a counter.
  • The second truck: lot full. A small and a compact spot are free, but no large one, so the truck is refused at the gate, not squeezed in. The first stack-trace line, EntryGate.lambda$enter$0, is the lambda inside enter (Java gives lambdas generated names like this).

9. The class diagram

A class diagram is a picture of the classes, what each one holds, and how they connect. It is the map an interviewer asks you to draw before coding. Here is the episode's diagram:

ParkingLot ──1..*──▶ ParkingFloor ──1..*──▶ ParkingSpot (id, SpotType)
     ▲                                             │ holds 0..1
     │ uses                                        ▼
EntryGate ──issues──▶ Ticket ──refers to──▶ Vehicle (abstract)
ExitGate  ──takes───▶ Ticket                ├─ Bike   needs SMALL
DisplayBoard ──reads free counts──▶ ParkingFloor  ├─ Car    needs COMPACT
                                            └─ Truck  needs LARGE

How to read it:

  • An arrow between two classes is an association: one class knows about (holds or uses) the other.
  • The numbers on an arrow are the multiplicity (episode 18): how many objects can be at that end. 1..* means "one or more": a lot has one or more floors; a floor has one or more spots. 0..1 means "zero or one": a spot holds no vehicle (free) or one vehicle.
  • EntryGate ── uses ──▶ ParkingLot: the gate is given the lot and asks it for spots.
  • Vehicle (abstract) with ├─ Bike, ├─ Car, └─ Truck below it is the inheritance part: each subclass is a Vehicle.

A fuller version, with the main fields and methods (+ = method, - = private field):

ParkingLot                  1 ──── 1..*   ParkingFloor               1 ──── 1..*   ParkingSpot
  - floors: List<ParkingFloor>              - number: int                          - id: String
  + findSpot(Vehicle): Optional             - spots: List<ParkingSpot>             - type: SpotType
                                            + findSpot(Vehicle): Optional          - parked: Vehicle  (0..1)
                                            + free(SpotType): long                 + isFree(), park(v), unpark(v)

EntryGate   - lot: ParkingLot     + enter(Vehicle, time): Ticket      (uses ParkingLot, issues Ticket)
ExitGate                          + exit(Ticket): Vehicle             (takes Ticket, frees its spot)
DisplayBoard                      + show(ParkingLot)                  (reads ParkingFloor.free)

Ticket (record)   id: int, vehicle: Vehicle, spot: ParkingSpot, entryTime: String

Vehicle (abstract)   - plate: String   + type(): VehicleType
   ▲ extends: Bike, Car, Truck

enum SpotType    { SMALL, COMPACT, LARGE }   + fits(VehicleType): boolean
enum VehicleType { BIKE, CAR, TRUCK }

Each class and its one job (its responsibility):

Class Kind Responsibility (what it owns) Does NOT do
ParkingLot class Holds the floors; finds a free fitting spot across all floors Print tickets, show counts
ParkingFloor class Holds its spots; finds a fitting spot on this floor; counts free spots per type Know about gates
ParkingSpot class Its id, its type, the parked vehicle; refuses a taken spot or a misfit Search for other spots
SpotType enum The spot sizes, in order; the fit rule fits(VehicleType) Store anything parked
VehicleType enum The fixed list of vehicle kinds
Vehicle abstract class The plate; declares type() Choose a spot
Bike, Car, Truck subclasses Say their own type
Ticket record Proof of parking: id, vehicle, spot, entry time; never changes Compute a price (part 2)
EntryGate class Ask the lot for a spot, take it, issue a ticket; refuse when full Know floor layouts
ExitGate class Take a ticket and free exactly its spot Search by plate
DisplayBoard class Read and print free counts per floor and type Keep its own count

Notice that the fit rule appears in one row, the free count in one row, and "is this spot taken" in one row. That is single source of truth applied to the whole design.

10. The full model, unfolded

The video folds code to fit the screen. Here is the whole part-1 model written out in full, with the safer neededBy fit rule, private fields with getters, and two fixes an interviewer may poke at:

  • Ticket ids with two gates. In section 8 each EntryGate has its own nextId, so two gates would both issue ticket 1 (see Common mistakes). Here one TicketNumbers object is shared by all gates.
  • A ticket used twice. In section 8, ExitGate frees whatever is in the spot, even if a different car parked there later. Here unpark checks that the ticket's vehicle is really in that spot.

main is the composition root (episode 16): the one place where the objects are created and connected, before any work starts. It builds one lot and passes it to both entry gates. try { ... } catch (IllegalStateException e) { ... } catches the exception so the program can print the message and keep going; e.getMessage() is the message text.

import java.util.*;

enum VehicleType { BIKE, CAR, TRUCK }

enum SpotType {
    SMALL, COMPACT, LARGE;                                   // ordered from smallest to largest
    static SpotType neededBy(VehicleType v) {                // the smallest spot each vehicle needs
        return switch (v) { case BIKE -> SMALL; case CAR -> COMPACT; case TRUCK -> LARGE; };
    }
    boolean fits(VehicleType v) { return compareTo(neededBy(v)) >= 0; }   // same size or bigger
}

abstract class Vehicle {                                     // the Vehicle hierarchy
    private final String plate;
    Vehicle(String plate) { this.plate = plate; }
    String plate() { return plate; }
    abstract VehicleType type();
    public String toString() { return type() + " " + plate; }
}
class Bike extends Vehicle  { Bike(String p)  { super(p); } VehicleType type() { return VehicleType.BIKE; } }
class Car extends Vehicle   { Car(String p)   { super(p); } VehicleType type() { return VehicleType.CAR; } }
class Truck extends Vehicle { Truck(String p) { super(p); } VehicleType type() { return VehicleType.TRUCK; } }

class ParkingSpot {
    private final String id;
    private final SpotType type;
    private Vehicle parked;                                  // null = free
    ParkingSpot(String id, SpotType type) { this.id = id; this.type = type; }
    String id() { return id; }
    SpotType type() { return type; }
    boolean isFree() { return parked == null; }
    boolean canTake(Vehicle v) { return isFree() && type.fits(v.type()); }
    void park(Vehicle v) {
        if (!isFree()) throw new IllegalStateException(id + " is taken by " + parked);
        if (!type.fits(v.type())) throw new IllegalArgumentException(v + " does not fit " + type + " spot " + id);
        parked = v;
    }
    void unpark(Vehicle v) {                                 // only the vehicle that is really there
        if (parked != v) throw new IllegalStateException(v + " is not parked in " + id);
        parked = null;
    }
    public String toString() { return id; }
}

class ParkingFloor {
    private final int number;
    private final List<ParkingSpot> spots = new ArrayList<>();
    ParkingFloor(int number, SpotType... types) {            // spot id F1-2 = floor 1, spot 2
        this.number = number;
        for (SpotType t : types) spots.add(new ParkingSpot("F" + number + "-" + (spots.size() + 1), t));
    }
    int number() { return number; }
    Optional<ParkingSpot> findSpot(Vehicle v) {              // first free spot that fits
        for (ParkingSpot s : spots) if (s.canTake(v)) return Optional.of(s);
        return Optional.empty();
    }
    long free(SpotType t) { return spots.stream().filter(s -> s.isFree() && s.type() == t).count(); }
}

class ParkingLot {
    private final List<ParkingFloor> floors;
    ParkingLot(List<ParkingFloor> floors) { this.floors = List.copyOf(floors); }
    List<ParkingFloor> floors() { return floors; }
    Optional<ParkingSpot> findSpot(Vehicle v) {              // floor 0 first, then floor 1, ...
        for (ParkingFloor f : floors) {
            Optional<ParkingSpot> s = f.findSpot(v);
            if (s.isPresent()) return s;
        }
        return Optional.empty();
    }
}

record Ticket(int id, Vehicle vehicle, ParkingSpot spot, String entryTime) {}

class TicketNumbers {                                        // ONE counter shared by every entry gate
    private int next = 1;
    int next() { return next++; }
}

class EntryGate {
    private final String name; private final ParkingLot lot; private final TicketNumbers numbers;
    EntryGate(String name, ParkingLot lot, TicketNumbers numbers) { this.name = name; this.lot = lot; this.numbers = numbers; }
    Ticket enter(Vehicle v, String time) {                   // find a spot, take it, print a ticket
        ParkingSpot s = lot.findSpot(v).orElseThrow(() -> new IllegalStateException("lot full for " + v));
        s.park(v);
        Ticket t = new Ticket(numbers.next(), v, s, time);
        System.out.println(name + " gate: ticket " + t.id() + ", " + v + " -> " + s + " at " + time);
        return t;
    }
}

class ExitGate {
    Vehicle exit(Ticket t) { t.spot().unpark(t.vehicle()); return t.vehicle(); }
}

class DisplayBoard {                                         // keeps no count of its own
    void show(ParkingLot lot) {
        for (ParkingFloor f : lot.floors()) {
            StringBuilder s = new StringBuilder("  floor " + f.number() + ":");
            for (SpotType t : SpotType.values()) s.append(" ").append(t).append(" ").append(f.free(t));
            System.out.println(s);
        }
    }
}

public class Main {
    public static void main(String[] args) {                 // the composition root: build once, pass in
        ParkingLot lot = new ParkingLot(List.of(
                new ParkingFloor(0, SpotType.SMALL, SpotType.COMPACT, SpotType.COMPACT),
                new ParkingFloor(1, SpotType.COMPACT, SpotType.LARGE)));
        TicketNumbers numbers = new TicketNumbers();
        EntryGate north = new EntryGate("north", lot, numbers), south = new EntryGate("south", lot, numbers);
        ExitGate exit = new ExitGate();
        DisplayBoard board = new DisplayBoard();

        Ticket car = north.enter(new Car("KA01"), "10:00");
        south.enter(new Truck("MH12"), "10:02");
        south.enter(new Bike("KA05"), "10:03");
        board.show(lot);

        System.out.println("exit: " + exit.exit(car));
        board.show(lot);

        try { exit.exit(car); } catch (IllegalStateException e) { System.out.println("refused: " + e.getMessage()); }
        try { north.enter(new Truck("DL05"), "10:10"); } catch (IllegalStateException e) { System.out.println("refused: " + e.getMessage()); }
    }
}

Output:

north gate: ticket 1, CAR KA01 -> F0-2 at 10:00
south gate: ticket 2, TRUCK MH12 -> F1-2 at 10:02
south gate: ticket 3, BIKE KA05 -> F0-1 at 10:03
  floor 0: SMALL 0 COMPACT 1 LARGE 0
  floor 1: SMALL 0 COMPACT 1 LARGE 0
exit: CAR KA01
  floor 0: SMALL 0 COMPACT 2 LARGE 0
  floor 1: SMALL 0 COMPACT 1 LARGE 0
refused: CAR KA01 is not parked in F0-2
refused: lot full for TRUCK DL05

Both gates share one lot and one ticket counter, so the ids run 1, 2, 3 across gates. Using the car's ticket a second time is refused. List.copyOf(floors) makes an unchangeable copy, so nobody outside can add or remove floors behind the lot's back. (Two gates running at exactly the same moment, on different threads, could still both pick the same spot: that race is part 2.)

11. The singleton parking lot debate

11.1 What a singleton is (episode 22)

A singleton is a class that allows only one object of itself to exist. It has:

  • a private constructor, so no other class can write new;
  • a static field holding the one object (static means it belongs to the class itself, not to any one object, so there is exactly one of it);
  • a static getInstance() method that always returns that same object.

11.2 The case for and against

For: there really is only one building, and every gate must see the same spots. One object, one shared state.

Against:

  • Global state. Global state is data that any code anywhere in the program can reach and change. SingletonLot.getInstance() can be called from any class, so you can't tell from the outside who changes the lot.
  • Hidden dependency. A dependency is something a class needs in order to work: an EntryGate needs a lot. If the gate calls getInstance() inside its methods, that need is hidden: its constructor doesn't show it, and you can't hand it a different lot.
  • Tests share it. A unit test is a small program that checks one piece of behaviour and reports PASS or FAIL. Tests should be isolated: each starts from a fresh, known state. A singleton survives from one test to the next, so one test's parked cars leak into the next test.
  • A second mall later? If the company opens a second mall in the same app, the class itself forbids a second lot.

11.3 Proving the test problem

import java.util.*;
class SingletonLot {                                               // the Singleton way (episode 22)
    private static final SingletonLot INSTANCE = new SingletonLot(2);
    private final List<String> parked = new ArrayList<>();  private final int capacity;
    private SingletonLot(int capacity) { this.capacity = capacity; }
    static SingletonLot getInstance() { return INSTANCE; }
    boolean park(String plate) { if (parked.size() == capacity) return false; parked.add(plate); return true; }
}
class ParkingLot {                                                 // a normal class: main decides how many exist
    private final List<String> parked = new ArrayList<>();  private final int capacity;
    ParkingLot(int capacity) { this.capacity = capacity; }
    boolean park(String plate) { if (parked.size() == capacity) return false; parked.add(plate); return true; }
}
public class Main {
    static void check(boolean ok, String test) { System.out.println((ok ? "PASS  " : "FAIL  ") + test); }
    public static void main(String[] args) {                       // each test expects a fresh, empty 2-spot lot
        SingletonLot s1 = SingletonLot.getInstance();
        check(s1.park("KA01") && s1.park("KA02"), "singleton,  test 1: two cars fit");
        SingletonLot s2 = SingletonLot.getInstance();
        check(s2.park("MH12"), "singleton,  test 2: a car fits in an empty lot");
        System.out.println("      s1 == s2 ? " + (s1 == s2));
        ParkingLot p1 = new ParkingLot(2);
        check(p1.park("KA01") && p1.park("KA02"), "new object, test 1: two cars fit");
        ParkingLot p2 = new ParkingLot(2);
        check(p2.park("MH12"), "new object, test 2: a car fits in an empty lot");
    }
}

Output:

PASS  singleton,  test 1: two cars fit
FAIL  singleton,  test 2: a car fits in an empty lot
      s1 == s2 ? true
PASS  new object, test 1: two cars fit
PASS  new object, test 2: a car fits in an empty lot
  • Singleton test 2 fails: a car doesn't fit in what should be an empty lot. s1 == s2 is true (== on objects asks "is this the very same object?"), so test 1's two cars are still parked.
  • With a normal class, each test makes its own lot: PASS and PASS.

And the "second mall" problem is a compile error. Same classes, with this main:

public class Main { public static void main(String[] args) {
    SingletonLot second = new SingletonLot(500);                         // a second mall?
}}

Output:

Main.java:15: error: SingletonLot(int) has private access in SingletonLot
    SingletonLot second = new SingletonLot(500);                         // a second mall?
                          ^
1 error

11.4 The usual answer: one object, created in the composition root

"Yes, the app needs exactly one lot, but don't enforce it with a singleton." Create one ParkingLot in main, the composition root (episode 16), and pass it to the gates through their constructors. That is dependency injection: a class receives what it needs from outside instead of fetching it itself. Section 10's main does exactly this.

Singleton getInstance() One object made in main, passed in
Exactly one lot in the app Forced by the class Chosen by main
Dependency visible in the gate's constructor No (hidden) Yes: EntryGate(ParkingLot lot)
Each test gets a fresh lot No: state leaks between tests Yes: new ParkingLot(2) per test
A second mall later Impossible without rewriting new ParkingLot(...) again
Who can change the lot Any code anywhere Only objects that were given it

When is a singleton acceptable? For something that truly must be one per program and has no state that tests care about (a logger, say), and even then many teams prefer the composition root. In an interview, saying "one instance, but created and passed in, not a singleton, because of testing and hidden dependencies" is the answer that scores.

12. Interview follow-ups for part 1

Follow-up Answer
Electric charging spots A new SpotType (or a "has charger" feature on a spot); the fit rule changes in one place (the mini project does it)
Reserved and accessible spots A flag on the spot (reservedFor, accessible), checked in canTake at entry
300 spots: first fit is slow Keep a free list per spot type (a ready queue of free spots) so finding one is instant: part 2
Two gates at the same time Two cars could be given one spot; make spot-taking atomic: part 2
Pricing and payment Pricing strategies (episode 34's Strategy pattern), computed at the exit gate: part 2
Find my car Keep a Map from plate to ticket; the ticket already knows the spot (mini project)
The quiz's wasted spot (a bike in a compact spot) Best fit: choose the smallest spot that fits (practice question 2)

Common mistakes

Mistake What you see Why Fix
Spots without a size truck MH12 -> spot 1 (a bike spot) No SpotType SpotType + fits()
A free counter kept by hand Display board: 2 free (really 3) A second copy of the truth Count from the spots
Parking a vehicle that doesn't fit java.lang.IllegalArgumentException: TRUCK MH12 does not fit SMALL spot F0-S1 The spot checks size Find a fitting spot first
Parking in a taken spot java.lang.IllegalStateException: F0-L1 is taken by BIKE KA01 The spot checks it is free Use findSpot, which only returns free spots
No fitting spot left java.lang.IllegalStateException: lot full: Vehicle[plate=DL05, type=TRUCK] Every LARGE spot is taken Refuse at the gate, show "full"
ParkingLot as a singleton FAIL singleton, test 2: a car fits in an empty lot Tests share one object One object in main, passed in
Fit rule by ordinal() across two enums TRUCK fits: (nothing), no error at all The rule depends on VehicleType's order neededBy switch + compareTo on SpotType
A switch that misses an enum value error: the switch expression does not cover all possible input values New enum value, switch not updated Add the case (the compiler found it for you)
new on the abstract class error: Vehicle is abstract; cannot be instantiated Abstract classes have no objects new Car("KA01")
A subclass that forgets type() error: Bus is not abstract and does not override abstract method type() in Vehicle Every abstract method must be filled in Add VehicleType type() to Bus
Reading a type from bad text java.lang.IllegalArgumentException: No enum constant VehicleType.SUV valueOf needs an exact name Validate input; list allowed values
Optional.get() on an empty box java.util.NoSuchElementException: No value present No spot fits; get() assumes one does orElseThrow with a clear message, or ifPresent/orElse
Using a ticket twice (episode's ExitGate) java.lang.NullPointerException: Cannot invoke "Vehicle.plate()" because the return value of "ExitGate.exit(Ticket)" is null The spot was already freed Check the ticket's vehicle is really in the spot
One nextId per gate Two different cars both get Ticket[id=1, ...] Each gate has its own counter One shared ticket counter, made in main
new on the singleton error: SingletonLot(int) has private access in SingletonLot The constructor is private Use a normal class, made in main

The less obvious ones, run for real. Each takes a program from above and replaces only main (so the line numbers count the whole file).

new on the abstract class (section 6.4's program, new main):

public class Main { public static void main(String[] args) {
    Vehicle v = new Vehicle("KA01");
}}
Main.java:25: error: Vehicle is abstract; cannot be instantiated
    Vehicle v = new Vehicle("KA01");
                ^
1 error

A subclass that forgets type() (section 6.4's program, with a Bus class added before main):

class Bus extends Vehicle { Bus(String p) { super(p); } }          // forgot type()
public class Main { public static void main(String[] args) { System.out.println(new Bus("KA09")); }}
Main.java:24: error: Bus is not abstract and does not override abstract method type() in Vehicle
class Bus extends Vehicle { Bus(String p) { super(p); } }          // forgot type()
^
1 error

Reading a type from bad text (section 6.4's program, new main):

public class Main { public static void main(String[] args) {
    VehicleType t = VehicleType.valueOf("SUV");
}}
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant VehicleType.SUV
    at java.base/java.lang.Enum.valueOf(Enum.java:293)
    at VehicleType.valueOf(Main.java:1)
    at Main.main(Main.java:25)

Optional.get() on an empty box (section 7's program, new main):

public class Main { public static void main(String[] args) {
    ParkingLot lot = new ParkingLot(List.of(new ParkingFloor(0, SpotType.SMALL)));
    ParkingSpot s = lot.findSpot(VehicleType.TRUCK).get();               // no LARGE spot exists
}}
Exception in thread "main" java.util.NoSuchElementException: No value present
    at java.base/java.util.Optional.get(Optional.java:143)
    at Main.main(Main.java:22)

Using a ticket twice (section 8's program, new main):

public class Main { public static void main(String[] args) {
    var lot = new ParkingLot(List.of(new ParkingFloor(0, SpotType.SMALL, SpotType.COMPACT)));
    var entry = new EntryGate(lot); var exit = new ExitGate();
    Ticket t1 = entry.enter(new Vehicle("KA01", VehicleType.CAR), "10:00");
    System.out.println("exit: " + exit.exit(t1).plate());
    System.out.println("exit: " + exit.exit(t1).plate());                 // the same ticket again
}}
exit: KA01
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Vehicle.plate()" because the return value of "ExitGate.exit(Ticket)" is null
    at Main.main(Main.java:26)

A NullPointerException is thrown when code calls a method on null. Here it is the lucky case: if another car had parked in F0-2 in between, the second exit would have silently freed that car's spot. Section 10's unpark(Vehicle) check closes the hole.

One nextId per gate (section 8's program, new main):

public class Main { public static void main(String[] args) {
    var lot = new ParkingLot(List.of(new ParkingFloor(0, SpotType.COMPACT, SpotType.COMPACT)));
    var north = new EntryGate(lot); var south = new EntryGate(lot);      // two gates, two counters
    System.out.println(north.enter(new Vehicle("KA01", VehicleType.CAR), "10:00"));
    System.out.println(south.enter(new Vehicle("KA02", VehicleType.CAR), "10:01"));
}}
Ticket[id=1, vehicle=Vehicle[plate=KA01, type=CAR], spot=F0-1, entryTime=10:00]
Ticket[id=1, vehicle=Vehicle[plate=KA02, type=CAR], spot=F0-2, entryTime=10:01]

Two different cars, two tickets numbered 1. The ticket counter is a fact about the lot, not about one gate, so it needs one owner shared by all gates.

Mini project: electric spots, find my car, and FULL on the board

The episode's homework, built on the full model. Goals:

  1. Add an ELECTRIC spot type (a car-sized spot with a charger) and an ELECTRIC_CAR vehicle type. Chargers are kept for electric cars; an electric car tries a charger first and otherwise takes any spot a car could use.
  2. Find my car by plate: keep a Map from plate to ticket. A Map stores key-value pairs and finds a value by its key quickly; HashMap is the usual kind. The same plate can't enter twice.
  3. The display board shows FULL instead of 0, and skips spot types a floor doesn't have.

Two design points:

  • ELECTRIC is not a size, so "spot order = size" no longer holds and compareTo can't be the fit rule any more. fits becomes an exhaustive switch over the spot type: still one place, just a different rule. This is exactly why section 7.2 warned against leaning on enum order.
  • The plate map is a second record of who is inside: an index (a lookup structure that answers a question fast). To keep a single source of truth in practice, the only ways in and out are ParkingLot.park and ParkingLot.release, which change the spot and the map together. The gates just call them.

ElectricCar extends Car shows a hierarchy more than one level deep: an electric car is a car, with a different type.

import java.util.*;

enum VehicleType { BIKE, CAR, ELECTRIC_CAR, TRUCK }

enum SpotType {
    SMALL, COMPACT, ELECTRIC, LARGE;                         // ELECTRIC = a car-sized spot with a charger
    boolean fits(VehicleType v) {                            // the ONE place the fit rule lives
        return switch (this) {
            case SMALL    -> v == VehicleType.BIKE;
            case COMPACT  -> v != VehicleType.TRUCK;
            case ELECTRIC -> v == VehicleType.ELECTRIC_CAR;  // chargers are kept for electric cars
            case LARGE    -> true;
        };
    }
}

abstract class Vehicle {
    private final String plate;
    Vehicle(String plate) { this.plate = plate; }
    String plate() { return plate; }
    abstract VehicleType type();
    public String toString() { return type() + " " + plate; }
}
class Bike extends Vehicle  { Bike(String p)  { super(p); } VehicleType type() { return VehicleType.BIKE; } }
class Car extends Vehicle   { Car(String p)   { super(p); } VehicleType type() { return VehicleType.CAR; } }
class ElectricCar extends Car { ElectricCar(String p) { super(p); } VehicleType type() { return VehicleType.ELECTRIC_CAR; } }
class Truck extends Vehicle { Truck(String p) { super(p); } VehicleType type() { return VehicleType.TRUCK; } }

class ParkingSpot {
    private final String id; private final SpotType type; private Vehicle parked;
    ParkingSpot(String id, SpotType type) { this.id = id; this.type = type; }
    String id() { return id; }
    SpotType type() { return type; }
    boolean isFree() { return parked == null; }
    boolean canTake(Vehicle v) { return isFree() && type.fits(v.type()); }
    void park(Vehicle v) {
        if (!canTake(v)) throw new IllegalArgumentException(v + " cannot use " + type + " spot " + id);
        parked = v;
    }
    void unpark(Vehicle v) {
        if (parked != v) throw new IllegalStateException(v + " is not parked in " + id);
        parked = null;
    }
    public String toString() { return id; }
}

class ParkingFloor {
    private final int number; private final List<ParkingSpot> spots = new ArrayList<>();
    ParkingFloor(int number, SpotType... types) {
        this.number = number;
        for (SpotType t : types) spots.add(new ParkingSpot("F" + number + "-" + (spots.size() + 1), t));
    }
    int number() { return number; }
    List<ParkingSpot> spots() { return spots; }
    long total(SpotType t) { return spots.stream().filter(s -> s.type() == t).count(); }
    long free(SpotType t)  { return spots.stream().filter(s -> s.type() == t && s.isFree()).count(); }
}

record Ticket(int id, Vehicle vehicle, ParkingSpot spot, String entryTime) {}

class ParkingLot {
    private final List<ParkingFloor> floors;
    private final Map<String, Ticket> byPlate = new HashMap<>();   // "find my car": plate -> ticket
    private int nextTicket = 1;
    ParkingLot(List<ParkingFloor> floors) { this.floors = List.copyOf(floors); }
    List<ParkingFloor> floors() { return floors; }

    private Optional<ParkingSpot> firstFit(Vehicle v, SpotType only) {
        for (ParkingFloor f : floors)
            for (ParkingSpot s : f.spots())
                if (s.canTake(v) && (only == null || s.type() == only)) return Optional.of(s);
        return Optional.empty();
    }
    Optional<ParkingSpot> findSpot(Vehicle v) {              // an electric car tries the chargers first
        if (v.type() == VehicleType.ELECTRIC_CAR) {
            Optional<ParkingSpot> charger = firstFit(v, SpotType.ELECTRIC);
            if (charger.isPresent()) return charger;
        }
        return firstFit(v, null);
    }
    Ticket park(Vehicle v, String time) {                    // the ONLY way in: spot and map change together
        if (byPlate.containsKey(v.plate())) throw new IllegalStateException(v.plate() + " is already inside");
        ParkingSpot s = findSpot(v).orElseThrow(() -> new IllegalStateException("lot full for " + v));
        s.park(v);
        Ticket t = new Ticket(nextTicket++, v, s, time);
        byPlate.put(v.plate(), t);
        return t;
    }
    Vehicle release(Ticket t) {                              // the ONLY way out
        t.spot().unpark(t.vehicle());
        byPlate.remove(t.vehicle().plate());
        return t.vehicle();
    }
    Optional<Ticket> findMyCar(String plate) { return Optional.ofNullable(byPlate.get(plate)); }
}

class EntryGate {
    private final ParkingLot lot;
    EntryGate(ParkingLot lot) { this.lot = lot; }
    Ticket enter(Vehicle v, String time) { return lot.park(v, time); }
}
class ExitGate {
    private final ParkingLot lot;
    ExitGate(ParkingLot lot) { this.lot = lot; }
    Vehicle exit(Ticket t) { return lot.release(t); }
}

class DisplayBoard {
    void show(ParkingLot lot) {
        for (ParkingFloor f : lot.floors()) {
            StringBuilder s = new StringBuilder("  floor " + f.number() + ":");
            for (SpotType t : SpotType.values()) {
                if (f.total(t) == 0) continue;                       // this floor has none of that type
                long free = f.free(t);
                s.append("  ").append(t).append(" ").append(free == 0 ? "FULL" : String.valueOf(free));
            }
            System.out.println(s);
        }
    }
}

public class Main {
    static void tryEnter(EntryGate g, Vehicle v, String time) {
        try { Ticket t = g.enter(v, time); System.out.println("in:  " + v + " -> " + t.spot() + " (ticket " + t.id() + ")"); }
        catch (RuntimeException e) { System.out.println("refused: " + e.getMessage()); }
    }
    public static void main(String[] args) {                         // composition root
        ParkingLot lot = new ParkingLot(List.of(
                new ParkingFloor(0, SpotType.SMALL, SpotType.COMPACT, SpotType.ELECTRIC),
                new ParkingFloor(1, SpotType.COMPACT, SpotType.LARGE)));
        EntryGate entry = new EntryGate(lot);
        ExitGate exit = new ExitGate(lot);
        DisplayBoard board = new DisplayBoard();

        tryEnter(entry, new Car("KA01"), "10:00");
        tryEnter(entry, new ElectricCar("KA02"), "10:01");
        tryEnter(entry, new ElectricCar("KA03"), "10:02");          // charger taken: a normal spot
        tryEnter(entry, new Car("KA01"), "10:03");                  // the same plate again
        tryEnter(entry, new Truck("MH12"), "10:04");
        tryEnter(entry, new Car("KA04"), "10:05");                  // only a SMALL and nothing else left
        board.show(lot);

        System.out.println("find KA02: " + lot.findMyCar("KA02").map(t -> "spot " + t.spot() + ", in since " + t.entryTime()).orElse("not here"));
        System.out.println("find DL09: " + lot.findMyCar("DL09").map(t -> "spot " + t.spot()).orElse("not here"));

        Ticket t = lot.findMyCar("KA02").orElseThrow();
        System.out.println("out: " + exit.exit(t));
        board.show(lot);
        System.out.println("find KA02: " + lot.findMyCar("KA02").map(x -> "spot " + x.spot()).orElse("not here"));
    }
}

Output:

in:  CAR KA01 -> F0-2 (ticket 1)
in:  ELECTRIC_CAR KA02 -> F0-3 (ticket 2)
in:  ELECTRIC_CAR KA03 -> F1-1 (ticket 3)
refused: KA01 is already inside
in:  TRUCK MH12 -> F1-2 (ticket 4)
refused: lot full for CAR KA04
  floor 0:  SMALL 1  COMPACT FULL  ELECTRIC FULL
  floor 1:  COMPACT FULL  LARGE FULL
find KA02: spot F0-3, in since 10:01
find DL09: not here
out: ELECTRIC_CAR KA02
  floor 0:  SMALL 1  COMPACT FULL  ELECTRIC 1
  floor 1:  COMPACT FULL  LARGE FULL
find KA02: not here

What to notice:

  • The first electric car got the charger F0-3; the second found the charger taken and took the compact F1-1, as a normal car would.
  • KA01 couldn't enter twice. KA04 was refused because only a SMALL spot was left.
  • Find my car answered from the map; after KA02 left, both the spot and the map were updated in the same release call, so the board shows ELECTRIC 1 and find-my-car says not here.
  • RuntimeException is the parent of both IllegalStateException and IllegalArgumentException, so one catch handles both. Optional.ofNullable(x) makes an empty box if x is null; orElseThrow() with no argument throws NoSuchElementException if the box is empty.

Practice

1. The video's quiz. Floor 0 has F0-1 COMPACT and F0-2 LARGE; floor 1 has F1-1 SMALL. All spots are free. A bike arrives, and findSpot is the first-fit version from section 7. Which spot does it get? Check it by running.

Answer

F0-1, the compact spot. First fit asks floor 0 first, and a bike fits a compact spot. Section 7's classes with this main:

public class Main { public static void main(String[] args) {
    ParkingLot lot = new ParkingLot(List.of(new ParkingFloor(0, SpotType.COMPACT, SpotType.LARGE),
                                            new ParkingFloor(1, SpotType.SMALL)));
    System.out.println("BIKE -> " + lot.findSpot(VehicleType.BIKE).map(s -> s.id).orElse("no spot"));
}}

Output:

BIKE -> F0-1

It works, but it wastes a car spot while a bike spot sits empty.

2. Write a best-fit bestSpot that picks the smallest free spot that fits, on any floor, and a lot-wide count of free spots per type. Run it on the quiz's lot with two bikes and a car.

Answer

min(Comparator.comparing(s -> s.type)) keeps the spot with the smallest type. A Comparator is an object that decides which of two items comes first; Comparator.comparing(f) compares items by the value f returns. An EnumMap is a Map whose keys are enum values, kept in declared order; merge(key, 1L, Long::sum) adds 1 to the value for that key.

import java.util.*;

enum VehicleType { BIKE, CAR, TRUCK }
enum SpotType { SMALL, COMPACT, LARGE;
    static SpotType neededBy(VehicleType v) { return switch (v) { case BIKE -> SMALL; case CAR -> COMPACT; case TRUCK -> LARGE; }; }
    boolean fits(VehicleType v) { return compareTo(neededBy(v)) >= 0; } }
class ParkingSpot { final String id; final SpotType type; String parked;   // plate, null = free
    ParkingSpot(String id, SpotType type) { this.id = id; this.type = type; } }
class ParkingFloor { final int number; final List<ParkingSpot> spots = new ArrayList<>();
    ParkingFloor(int number, SpotType... types) { this.number = number;
        for (SpotType t : types) spots.add(new ParkingSpot("F" + number + "-" + (spots.size() + 1), t)); } }
record ParkingLot(List<ParkingFloor> floors) {
    Optional<ParkingSpot> bestSpot(VehicleType v) {          // the SMALLEST free spot that fits, on any floor
        return floors.stream().flatMap(f -> f.spots.stream())
                .filter(s -> s.parked == null && s.type.fits(v))
                .min(Comparator.comparing((ParkingSpot s) -> s.type));   // ties: the first one found wins
    }
    Map<SpotType, Long> freeByType() {                       // lot-wide free count, per type
        Map<SpotType, Long> m = new EnumMap<>(SpotType.class);
        for (SpotType t : SpotType.values()) m.put(t, 0L);
        for (ParkingFloor f : floors) for (ParkingSpot s : f.spots) if (s.parked == null) m.merge(s.type, 1L, Long::sum);
        return m;
    }
}
public class Main {
    public static void main(String[] args) {
        ParkingLot lot = new ParkingLot(List.of(new ParkingFloor(0, SpotType.COMPACT, SpotType.LARGE),
                                                new ParkingFloor(1, SpotType.SMALL)));
        for (String[] in : new String[][]{ {"BIKE", "KA01"}, {"BIKE", "KA02"}, {"CAR", "KA03"} }) {
            VehicleType v = VehicleType.valueOf(in[0]);
            Optional<ParkingSpot> s = lot.bestSpot(v);
            s.ifPresent(x -> x.parked = in[1]);
            System.out.println(v + " " + in[1] + " -> " + s.map(x -> x.id + " (" + x.type + ")").orElse("no spot"));
        }
        System.out.println("free: " + lot.freeByType());
    }
}

Output:

BIKE KA01 -> F1-1 (SMALL)
BIKE KA02 -> F0-1 (COMPACT)
CAR KA03 -> F0-2 (LARGE)
free: {SMALL=0, COMPACT=0, LARGE=0}

The first bike now takes the small spot on floor 1. Best fit saves big spots for big vehicles, at the cost of scanning every spot (part 2 makes this fast with free lists).

3. Sort each of these into functional or non-functional: (a) "the exit gate frees the ticket's spot", (b) "finding a spot takes under a second with 300 spots", (c) "a truck is never given a small spot", (d) "adding a new vehicle type changes one class".

Answer

(a) functional (a behaviour), (b) non-functional (speed), (c) functional (a rule the system enforces), (d) non-functional (ease of change, also called extensibility).

4. Why does ExitGate.exit take a Ticket and not a plate?

Answer

The ticket already holds the spot, so the exit is direct: no search across floors, and no doubt about which spot to free. It is also proof: a plate can be typed by anyone, a ticket was issued by the entry gate. ("Find my car" by plate is a separate, optional feature built on a map from plate to ticket.)

5. In section 8's code, what would go wrong if DisplayBoard kept its own int free per floor and the gates updated it?

Answer

It would be Ramesh's chalk board again: a second copy of the truth. Any path that changes a spot without updating the board (a new gate, a staff override, a bug in exit) makes the board lie, exactly as leave did in section 3. Counting from the spots each time means there is nothing to forget. If counting ever became too slow, the counter would have to live inside the same method that changes the spot, so the two can't drift.

6. A colleague writes boolean fits(VehicleType v) { return ordinal() >= v.ordinal(); }. It passes every test today. What do you say in review?

Answer

It only works because VehicleType and SpotType happen to be declared in matching order. Adding a value to VehicleType (like SCOOTER in the middle) silently breaks it: section 7.2 showed TRUCK fits: with nothing, and no error. Ask for an explicit neededBy switch (exhaustive, so the compiler catches a new type) and compareTo only between spot types, whose order really means size.

7. Rewrite the singleton test so it passes without changing SingletonLot to a normal class. Why is this worse?

Answer

You would add a reset() method that clears parked, and call it at the start of each test. It's worse because every test must remember to call it (forget once and tests depend on each other's order), production code gains a method only tests need, and the hidden dependency and the "one mall only" limit are still there. Creating a new ParkingLot per test fixes all three at once.

Quick quiz

  1. Floor 0: F0-1 COMPACT, F0-2 LARGE. Floor 1: F1-1 SMALL. All free. A bike arrives; findSpot is first fit, floor 0 first. Which spot? (A) F1-1 (B) F0-1 (C) F0-2 (D) no spot
Answer

(B) F0-1. First fit asks floor 0 first, and a bike fits a compact spot, even though a small spot is free on floor 1 (practice 1 ran it). Smarter allocation is part 2.

  1. In a class diagram, what does 1..* on the arrow from ParkingFloor to ParkingSpot mean?
Answer

Multiplicity "one or more": each floor has at least one spot, with no upper limit.

  1. In section 8's program, a car exits. Which line of code updates the display board's count?
Answer

None. The board keeps no count: free(SpotType) counts free spots from the spots every time show runs. Freeing the spot is the only change needed. That's a single source of truth.

  1. What does SingletonLot.getInstance() == SingletonLot.getInstance() print?
Answer

true. It is the same object every time, which is why the second test saw the first test's cars.

Interview questions

  1. What requirements would you gather for a parking lot? Functional: floors with spots, three spot types, three vehicle types with a fit rule (smaller vehicles may use bigger spots), an entry gate that issues a ticket, an exit gate that frees the spot, a display board per floor and type. Non-functional: fast spot search, correct with several gates at once, easy to extend, a board that is always right. Then clarifying questions (bike in a car spot? electric spots? pricing?) and an explicit scope.
  2. What are the core classes and their responsibilities? ParkingLot (floors, find a spot), ParkingFloor (spots, find and count), ParkingSpot (id, type, parked vehicle, refuses misfits), SpotType/VehicleType enums, abstract Vehicle with Bike/Car/Truck, Ticket (id, vehicle, spot, entry time), EntryGate, ExitGate, DisplayBoard.
  3. Where does the "does this vehicle fit this spot" rule live, and why? In SpotType.fits (the rule) and enforced by ParkingSpot.park (the guard). One place, so no gate or caller can bypass it, and a new spot type changes one method.
  4. Subclasses for vehicles, or one class with a type field? If kinds differ only by size, a type field is simpler; if they have their own data or behaviour, subclasses. Mention sealed classes plus pattern switches to get exhaustiveness with subclasses. Pick one, justify it, say when you'd change.
  5. Why is comparing ordinal() values risky? It ties a rule to declaration order. Inserting a new enum value silently changes the results with no error. Use an explicit mapping (exhaustive switch) and only compare values whose order has meaning.
  6. How does the display board stay correct? It derives the count from the spots each time instead of keeping its own counter: a single source of truth.
  7. Should ParkingLot be a singleton? The app needs one lot, but don't enforce it with a singleton: it's global state, it hides the gates' dependency, tests leak state into each other, and a second mall becomes impossible. Create one lot in the composition root (main) and inject it into the gates' constructors.
  8. Two entry gates both issue ticket 1. Why, and how do you fix it? Each gate had its own counter. The ticket number belongs to the lot, so one shared counter (made in main, or owned by the lot) issues all ids.
  9. How would you add electric charging spots? A new spot type (or a charger feature on spots) and a change to the fit rule in one place; optionally a preference so electric cars try chargers first (the mini project).
  10. What happens when two cars arrive at two gates at the same instant? Both could see the same free spot and both take it. Taking a spot must be atomic (one check-and-take step that can't be interrupted): part 2 covers locking and other fixes.

Glossary

Term Meaning, with an example
Low-Level Design (LLD) Designing the classes, their fields, methods and connections for one system
Machine-coding round An interview round where you design and code a small working system in about 60-120 minutes
Requirement One thing the system must do, or a quality it must have: "a truck never gets a small spot"
Parking lot requirements The agreed list of functional and non-functional requirements, clarifying answers and scope for our parking lot (section 4)
Functional requirement A behaviour the system performs or a rule it enforces: "the exit gate frees the ticket's spot"
Non-functional requirement A quality the system must have, not a feature: "finding a spot is fast"
Clarifying question A question to the interviewer that removes a doubt in the brief: "can a bike use a car spot?"
Assumption The answer you write down for a clarifying question, so the design has a fixed rule
Scope The part of the problem you agree to build now: model, park, exit, display
Out of scope What you agree to leave out, said out loud: payments in part 1, a mobile app
Concurrency Several things running at the same time, like two gates serving cars at once
Atomic Done as one step that can't be interrupted halfway: check-and-take a spot
Noun analysis Picking candidate classes from the nouns in the requirements (episode 20): lot, floor, spot, ticket
Entity A thing the system must remember or act as; usually becomes a class
Responsibility The one job a class owns: ParkingSpot owns "refuse a misfit"
ParkingLot The whole building: holds the floors and finds a free fitting spot across them
ParkingFloor One level: holds its spots, finds a fitting spot on that level, counts free spots per type
ParkingSpot One painted bay: an id like F0-2, a SpotType, and the vehicle parked there (or null)
Spot types The fixed spot sizes SMALL, COMPACT, LARGE (plus ELECTRIC in the mini project), as enum SpotType
SpotType The enum of spot types, ordered smallest to largest, with the fit rule fits(VehicleType)
VehicleType The enum of vehicle kinds: BIKE, CAR, TRUCK
Fit rule A spot fits a vehicle if the spot is at least the size the vehicle needs: a bike fits LARGE, a truck doesn't fit SMALL
neededBy Our method mapping each vehicle type to the smallest spot it needs: neededBy(CAR) is COMPACT
Vehicle hierarchy An abstract Vehicle class (the plate, an abstract type()) with subclasses Bike, Car, Truck
Type field A field whose value says what kind an object is: record Vehicle(String plate, VehicleType type)
Ticket The proof of parking: a record of id, vehicle, spot and entry time: Ticket[id=1, ..., spot=F0-2, entryTime=10:00]
EntryGate Finds a free fitting spot, takes it and issues a ticket; refuses with "lot full"
ExitGate Takes a ticket back and frees exactly that ticket's spot
DisplayBoard Prints free spots per floor and type, counted live from the spots, never stored
First fit Take the first free spot that fits, in order (floor 0 first)
Best fit Take the smallest free spot that fits, so big spots stay for big vehicles
Free list A ready collection of free spots per type, so one can be taken without scanning (part 2)
Index A lookup structure that answers one question fast, like a map from plate to ticket
Class diagram A picture of the classes, their fields and methods, and how they connect (section 9)
Association A line between two classes meaning one holds or uses the other: EntryGate uses ParkingLot
Multiplicity How many objects can be at one end of an association (episode 18): 1..*, 0..1
1..* "One or more": a lot has one or more floors
0..1 "Zero or one": a spot holds no vehicle or one
Class hierarchy A family of classes where specific ones extend general ones: Truck extends Vehicle
Inheritance A subclass gets its superclass's fields and methods: Car gets plate from Vehicle
Superclass / subclass The class being extended (Vehicle) / the class extending it (Car)
Abstract class A class you can't create objects of, made to be extended: new Vehicle(...) is a compile error
Abstract method A method with no body that each subclass must fill in: abstract VehicleType type();
Override A subclass providing its own body for an inherited method: Car's type() returns CAR
Sealed class A class that lists exactly which subclasses are allowed: sealed abstract class Vehicle permits Bike, Car, Truck
Final (class) A class that can't be extended: final class Bike
Final (field) A field set once and never changed: private final String plate
Private Visible only inside its own class: private Vehicle parked
Static Belongs to the class itself, not to one object, so there is exactly one: static SpotType neededBy(...)
Encapsulation Hiding data behind methods so only the class can change it: parked is private, park() guards it
Constructor The special method that sets up a new object: ParkingSpot(String id, SpotType type)
super(...) Calls the parent class's constructor: super(p) stores the plate in Vehicle
toString() The method Java calls to turn an object into text: a truck prints as TRUCK MH12
Enum A type with a fixed list of named values: SpotType.LARGE; any other value won't compile
ordinal() An enum value's position in its list: SpotType.COMPACT.ordinal() is 1
values() Returns all of an enum's values in declared order: SpotType.values()
valueOf Turns a name into an enum value: VehicleType.valueOf("CAR"); a wrong name throws IllegalArgumentException
compareTo Compares two values: negative if the first is smaller, 0 if equal, positive if bigger; for enums, by declared order
Switch expression A switch that produces a value: switch (v) { case BIKE -> SMALL; ... }
Exhaustive A switch that covers every possible value; for enums and sealed classes the compiler checks it
Pattern-matching switch A switch that checks an object's class: case Truck t -> LARGE
Record A short class that only carries values; Java writes its constructor, getters, equals, hashCode, toString: record Ticket(...)
null Java's "nothing here" value: parked == null means the spot is free
Optional A box holding one value or nothing: Optional.of(spot) or Optional.empty(); replaces returning null
isPresent / ifPresent Asks whether the Optional holds a value / runs code only if it does
map / orElse Transforms the value if present / gives the value, or a default if empty: .map(s -> s.id).orElse("no spot")
orElseThrow Gives the value, or throws an exception if the Optional is empty
Optional.ofNullable Makes an empty Optional from null, a full one otherwise
Lambda A small unnamed function passed to a method: s -> s.id
Stream A pipeline that processes a collection's items step by step: spots.stream().filter(...).count()
filter / count / findFirst Stream steps: keep matching items / count them / give the first as an Optional
flatMap Turns a stream of groups into one stream of their items: floors into all spots
min Stream step that keeps the smallest item by a Comparator
Comparator An object that decides which of two items comes first: Comparator.comparing(s -> s.type)
var Lets Java work out a local variable's type: var lot = new ParkingLot(...)
Varargs A parameter taking any number of arguments: SpotType... types
List, ArrayList An ordered collection / the usual growable one: new ArrayList<>()
List.of / List.copyOf Make an unchangeable list from values / from another list
Map, HashMap Key-value storage that finds a value by its key / the usual kind: plate → ticket
EnumMap A Map whose keys are enum values, kept in declared order
StringBuilder Builds text piece by piece with append
Exception Java's way of stopping normal flow because something should not happen
IllegalArgumentException Thrown when a method gets a bad argument: a truck for a small spot
IllegalStateException Thrown when an object's state doesn't allow the call: a taken spot, a full lot
NullPointerException Thrown when code calls a method on null: using a ticket twice in section 8
NoSuchElementException Thrown by Optional.get() on an empty box: "No value present"
RuntimeException The parent of the exceptions above; one catch (RuntimeException e) handles all of them
try / catch Runs code and handles a thrown exception instead of crashing: catch (IllegalStateException e)
Stack trace The chain of method calls, with line numbers, printed with an uncaught exception
Compile error An error javac reports before the program runs: "Vehicle is abstract; cannot be instantiated"
Single source of truth Each fact is stored in exactly one place and everything else reads it there: "is F0-2 free?" lives only in the spot
Derived value A value worked out from the source each time, not stored: the board's free count
Folded code Earlier code squeezed into a few lines at the top of a screen so the new part fits
Singleton A class that allows only one object: private constructor, static instance, getInstance() (episode 22)
getInstance() The static method of a singleton that always returns the same object
Private constructor A constructor no other class can call, so no one else can write new
Singleton parking lot debate Should ParkingLot be a singleton? For: one building, shared state. Against: global state, hidden dependency, leaky tests, no second mall. Usual answer: one object, made in main and passed in
Global state Data any code anywhere can reach and change, like a singleton's fields
Dependency Something a class needs to work: an EntryGate needs a ParkingLot
Hidden dependency A dependency fetched inside the code (getInstance()), not visible in the constructor
Dependency injection Giving a class what it needs from outside, usually through its constructor: new EntryGate(lot)
Composition root The one place, usually main, where all objects are created and connected (episode 16)
Unit test A small program that checks one piece of behaviour and reports PASS or FAIL
Test isolation Each test starts from a fresh, known state and can't be affected by other tests
== (on objects) "Is this the very same object?": s1 == s2 is true for a singleton
Strategy pattern Interchangeable algorithms behind one interface (episode 34); used for pricing in part 2

Summary

  • The obvious code (an array of strings and a hand-kept counter) put a truck in a bike spot and showed 2 free when 3 were free: no sizes, no types, a second copy of the truth, and no ticket.
  • Before code, write requirements: functional (what it does), non-functional (how well), clarifying questions with written assumptions, and a clear scope.
  • Noun analysis gives the entities: ParkingLot, ParkingFloor, ParkingSpot, SpotType, the Vehicle hierarchy, Ticket, EntryGate, ExitGate, DisplayBoard.
  • SpotType is ordered smallest to largest; a spot fits if it is at least the size the vehicle needs. The spot itself refuses a misfit or a taken spot.
  • Subclasses vs a type field: a type field is enough when kinds differ only in data; subclasses when they differ in data or behaviour; sealed classes give both exhaustiveness and separate classes.
  • ordinal() across two enums only works while their orders happen to line up; an explicit, exhaustive neededBy switch makes the compiler catch new types.
  • Floors and the lot find the first free spot that fits, floor by floor, returning an Optional.
  • Tickets prove who parked where and when; the ExitGate frees exactly the ticket's spot; the DisplayBoard counts live from the spots: a single source of truth.
  • The class diagram shows ParkingLot 1..* ParkingFloor 1..* ParkingSpot, a spot holding 0..1 vehicle, gates issuing and taking tickets, and the vehicle hierarchy.
  • Singleton debate: the app needs one lot, but a singleton is global state with a hidden dependency, and it leaked test 1's cars into test 2 (FAIL). Create one object in the composition root and pass it in.

Next episode: Design a Parking Lot, part 2, with spot allocation strategies, pricing, payment, the ticket's life from entry to exit, and two gates booking at the same moment.