Skip to content
Java project #13Intermediate

Vehicle Rental System

A fleet of cars, bikes and trucks in a sealed class hierarchy with polymorphic pricing, a template-method cost formula, rentals, returns and revenue reports.

Estimated time
~5 hours to build
Files
6 files · 414 lines
Technologies
Java 21, Sealed classes, Abstract classes, Pattern matching for switch, Records

Introduction

A rental agency rents very different vehicles, but every rental follows the same steps: daily rate, discounts, distance charges and late fees. This project expresses the shared formula once in an abstract base class and lets each vehicle type supply its own rates — inheritance and polymorphism doing exactly what they are for.

Problem statement

Model cars (economy, seven-seater or luxury), bikes (by engine size) and trucks (by tonnage) with different daily rates and distance rules. Implement quotes, renting (1–30 days, only if available), returning with distance and days late, and a revenue report by vehicle type. Apply a 15% discount for rentals of a week or more, charge 150% of the daily rate per late day, add a fixed insurance fee for trucks, and show which driving licence each vehicle needs.

Objectives

  • Design an abstract, sealed class hierarchy
  • Use the template-method pattern for a shared algorithm
  • Override methods to vary behaviour by subtype
  • Use an exhaustive pattern-matching switch over sealed types

Features

  • Three vehicle types with their own pricing rules
  • Weekly discount, late fees and truck insurance
  • Rent/return workflow with receipts
  • Revenue by vehicle type and licence requirements

Concepts demonstrated

  • Inheritance
  • Polymorphism
  • Template method pattern
  • Sealed hierarchies
  • Exhaustive switches

System architecture

Vehicle is sealed abstract and permits Car, Bike and Truck. It declares abstract dailyRate and distanceCharge and a concrete rentalCost (the template method) that combines them with the weekly discount and late fees; Truck overrides rentalCost to add a fixed fee via super. RentalAgency holds the fleet, the active rentals and completed receipts; licenceNeeded switches over the sealed type with no default branch.

TextArchitecture diagram
Vehicle (sealed, abstract)
dailyRate() distanceCharge(km) rentalCost(days, km, late)
/ | \
Car Bike Truck
seats, luxury cc tonnes (+ fixed fee)

Folder structure

TextProject tree
vehicle-rental-system/
├── README.md
├── src/Main.java
├── src/RentalAgency.java
├── src/Vehicle.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Main.java

72 lines
Javasrc/Main.java
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
/**
* Vehicle Rental System — a fleet of cars, bikes and trucks with polymorphic pricing.
*
* Commands:
* fleet available [car|bike|truck] rent ID CUSTOMER DAYS
* return ID KM DAYS_LATE quote ID DAYS KM report quit
*/
public class Main {
public static void main(String[] args) {
RentalAgency agency = new RentalAgency();
agency.add(new Car("C01", "Swift", 5, false));
agency.add(new Car("C02", "Innova Crysta", 7, false));
agency.add(new Car("C03", "BMW 3 Series", 5, true));
agency.add(new Bike("B01", "Activa", 110));
agency.add(new Bike("B02", "Royal Enfield 500", 499));
agency.add(new Truck("T01", "Tata 407", 2.5));
Scanner in = new Scanner(System.in);
System.out.println("=== Vehicle Rentals ===");
while (true) {
System.out.print("> ");
if (!in.hasNextLine()) break;
String[] p = in.nextLine().trim().split("\\s+");
System.out.println();
try {
switch (p[0].toLowerCase()) {
case "fleet" -> agency.all().forEach(v -> System.out.println(" " + v + " licence: " + RentalAgency.licenceNeeded(v)));
case "available" -> {
var list = agency.available(p.length > 1 ? p[1] : "");
if (list.isEmpty()) System.out.println(" nothing available");
list.forEach(v -> System.out.println(" " + v));
}
case "rent" -> {
RentalAgency.Rental r = agency.rent(p[1], p[2], Integer.parseInt(p[3]));
System.out.printf("Rental #%d: %s takes %s %s for %d day(s)%n", r.id(), r.customer(), r.vehicle().kind(), r.vehicle().model(), r.days());
}
case "return" -> {
RentalAgency.Receipt rc = agency.giveBack(p[1], Integer.parseInt(p[2]), Integer.parseInt(p[3]));
Vehicle v = rc.rental().vehicle();
System.out.printf("Receipt #%d %s: %d day(s), %d km, %d day(s) late -> Rs %,d%n", rc.rental().id(), v.model(), rc.rental().days(), rc.km(), rc.daysLate(), rc.amount());
}
case "quote" -> {
Vehicle v = agency.vehicle(p[1]);
int days = Integer.parseInt(p[2]), km = Integer.parseInt(p[3]);
System.out.printf("Quote for %s (%s): %d day(s), %d km = Rs %,d (distance part Rs %,d)%n", v.model(), v.kind(), days, km, v.rentalCost(days, km, 0), v.distanceCharge(km));
}
case "report" -> {
Map<String, Long> byKind = new TreeMap<>();
long total = 0;
for (RentalAgency.Receipt rc : agency.completed()) {
byKind.merge(rc.rental().vehicle().kind(), rc.amount(), Long::sum);
total += rc.amount();
}
byKind.forEach((k, v) -> System.out.printf(" %-6s Rs %,8d%n", k, v));
System.out.printf(" Total Rs %,8d from %d rental(s)%n", total, agency.completed().size());
}
case "quit" -> { return; }
default -> System.out.println("Commands: fleet available rent return quote report quit");
}
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
System.out.println("Error: missing or invalid arguments");
} catch (IllegalArgumentException | IllegalStateException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}

What each file does

src/Vehicle.java
The sealed abstract Vehicle and its three final subclasses with their pricing rules.
src/RentalAgency.java
Fleet, rentals, returns, availability and the exhaustive licence switch.
src/Main.java
Creates the fleet and runs the command loop and report.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Vehicle Rentals ===
>
C01 Car Swift Rs 2,000/day licence: LMV (car)
C02 Car Innova Crysta Rs 2,800/day licence: LMV (car)
C03 Car* BMW 3 Series Rs 4,500/day licence: LMV (car)
B01 Bike Activa Rs 600/day licence: MCWG (motorcycle)
B02 Bike Royal Enfield 500 Rs 1,200/day licence: MCWG (motorcycle)
T01 Truck Tata 407 Rs 4,250/day licence: HMV (heavy vehicle)
>
Quote for Swift (Car): 3 day(s), 400 km = Rs 7,800 (distance part Rs 1,800)
>
Quote for BMW 3 Series (Car*): 7 day(s), 100 km = Rs 26,775 (distance part Rs 0)
>
Quote for Royal Enfield 500 (Bike): 2 day(s), 300 km = Rs 3,000 (distance part Rs 600)
>
Quote for Tata 407 (Truck): 1 day(s), 120 km = Rs 7,010 (distance part Rs 1,260)
>
Rental #1: Asha takes Car Swift for 3 day(s)
>
Error: C01 is already rented
>
Rental #2: Ravi takes Bike Royal Enfield 500 for 2 day(s)
>
Rental #3: Meera takes Truck Tata 407 for 1 day(s)
>
Error: rentals are 1-30 days
>
C02 Car Innova Crysta Rs 2,800/day
C03 Car* BMW 3 Series Rs 4,500/day
>
B01 Bike Activa Rs 600/day
C02 Car Innova Crysta Rs 2,800/day
C03 Car* BMW 3 Series Rs 4,500/day
>
Receipt #1 Swift: 3 day(s), 400 km, 0 day(s) late -> Rs 7,800
>
Receipt #2 Royal Enfield 500: 2 day(s), 300 km, 1 day(s) late -> Rs 4,800
>
Receipt #3 Tata 407: 1 day(s), 120 km, 0 day(s) late -> Rs 7,010
>
Error: C03 is not rented
>
Bike Rs 4,800
Car Rs 7,800
Truck Rs 7,010
Total Rs 19,610 from 3 rental(s)
>
Input
fleet
quote C01 3 400
quote C03 7 100
quote B02 2 300
quote T01 1 120
rent C01 Asha 3
rent C01 Ravi 2
rent B02 Ravi 2
rent T01 Meera 1
rent C02 John 45
available car
available
return C01 400 0
return B02 300 1
return T01 120 0
return C03 10 0
report
quit

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • BMW for 7 days: 4,500 × 7 × 0.85 = ₹26,775 (weekly discount).
  • The Royal Enfield returned one day late: 2,400 + 600 km charge + 1,800 late fee = ₹4,800.
  • The truck adds a ₹1,500 insurance fee to 4,250 + 1,260 = ₹7,010.

Common errors

class is not allowed to extend sealed class

Every subclass must be listed in permits and declared final, sealed or non-sealed.

Truck price misses the base charges

When overriding rentalCost, call super.rentalCost(...) and add to it.

Possible improvements

  • Add electric vehicles with charging fees
  • Support reservations for future dates
  • Apply loyalty discounts per customer

Additional challenges

  1. 1Add a Van subclass and make the compiler point out every switch that must change.
  2. 2Track vehicle maintenance after every 5,000 km.
  3. 3Print a monthly utilisation report per vehicle.

Built and tested it yourself? Mark it to update your dashboard.