IntermediateLesson 11 of 206 min read

Generics, Records and Enums: Safer Types With Less Code

Learn generic classes and methods, records for plain data and enums for fixed sets of values, and see the compiler catch mistakes that would otherwise appear at run time.

In this lesson you will

  • Write a generic class and method
  • Use records for data
  • Model fixed choices with enums
  • Read a real compiler error

About 28 minutes

A booking is just data

Hana’s Booking class has six fields, a constructor, getters, equals, hashCode and toString, around sixty lines of code for something that only carries data. And her status field is a String where a typo such as “retruned” compiles happily and breaks the report later. Modern Java has tools for exactly these two problems: records and enums. A third tool, generics, lets you write a container once and have the compiler check what goes into it.

A record is a short way to declare an immutable data class. Writing record Booking(String bike, int days) gives you a constructor, accessors named bike() and days(), and equals, hashCode and toString that compare and print all the fields. An enum is a type with a fixed list of values, such as FREE, RENTED and REPAIR, and enums can carry fields and methods. A generic class declares a type parameter in angle brackets, as in class Box, so that one class can hold a String in one place and an Integer in another with the compiler tracking which is which.

Feature Replaces Benefit
record A class with fields, constructor, getters, equals, hashCode, toString Less code and immutability
enum Strings or ints that stand for a choice The compiler knows every valid value
generics Casts from Object Errors at compile time, not run time
import java.util.*;

enum Status {
    FREE("available"), RENTED("out with a customer"), REPAIR("in the workshop");
    private final String text;
    Status(String text) { this.text = text; }
    String text() { return text; }
}
record Booking(String bike, int days, Status status) {
    Booking {
        if (days < 1) throw new IllegalArgumentException("days must be at least 1");
    }
    int price() { return days * 1200; }
}
class Box<T> {
    private final List<T> items = new ArrayList<>();
    void add(T item) { items.add(item); }
    T first() { return items.get(0); }
    int size() { return items.size(); }
}
public class Main {
    static <T extends Comparable<T>> T biggest(List<T> list) {
        T best = list.get(0);
        for (T t : list) if (t.compareTo(best) > 0) best = t;
        return best;
    }
    public static void main(String[] args) {
        Booking b = new Booking("City 1", 3, Status.RENTED);
        Booking same = new Booking("City 1", 3, Status.RENTED);
        System.out.println(b);
        System.out.println("equal records: " + b.equals(same) + ", same hash: " + (b.hashCode() == same.hashCode()) + ", price " + b.price());
        System.out.println("status text: " + b.status().text() + ", ordinal " + b.status().ordinal() + ", all: " + Arrays.toString(Status.values()));
        System.out.println("valueOf: " + Status.valueOf("REPAIR") + ", switch: " + switch (b.status()) { case FREE -> "can rent"; case RENTED -> "wait"; case REPAIR -> "no"; });
        try { new Booking("X", 0, Status.FREE); } catch (IllegalArgumentException e) { System.out.println("rejected: " + e.getMessage()); }
        try { Status.valueOf("RETRUNED"); } catch (IllegalArgumentException e) { System.out.println("typo caught at run time: " + e.getMessage()); }
        Box<String> names = new Box<>(); names.add("City 1"); names.add("Trail 2");
        Box<Integer> days = new Box<>(); days.add(3);
        System.out.println("box sizes: " + names.size() + " and " + days.size() + ", first name length " + names.first().length());
        System.out.println("biggest string: " + biggest(List.of("trail", "city", "tandem")) + ", biggest int: " + biggest(List.of(4, 9, 2)));
    }
}
Booking[bike=City 1, days=3, status=RENTED]
equal records: true, same hash: true, price 3600
status text: out with a customer, ordinal 1, all: [FREE, RENTED, REPAIR]
valueOf: REPAIR, switch: wait
rejected: days must be at least 1
typo caught at run time: No enum constant Status.RETRUNED
box sizes: 2 and 1, first name length 6
biggest string: trail, biggest int: 9
import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("City 1");
        names.add(42);
    }
}
Main.java:6: error: incompatible types: int cannot be converted to String
        names.add(42);
                  ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

The record printed itself as “Booking[bike=City 1, days=3, status=RENTED]” with no toString code written by us, and two records with the same fields are equal and have the same hash code, which is what a data class needs. The compact constructor, the block that starts with the name Booking, validates the input, and a booking for 0 days was rejected with a clear message. The enum carries a text for each value. Its ordinal, the position in the list, is 1 for RENTED, and the switch expression over an enum has no default branch, since the compiler knows all three values are covered, so adding a fourth status later makes every such switch fail to compile until it is handled, which is exactly the safety you want.

The typo test is instructive. Status.valueOf(“RETRUNED”) fails at run time with an exception, but a typo in the code, Status.RETRUNED, would not compile at all. That is why enums beat strings for fixed choices: the compiler checks every use. The generic Box holds names in one place and numbers in another, with sizes 2 and 1, and the method biggest works for strings and integers alike because both implement Comparable. It gave “trail” for the strings and 9 for the integers.

The last experiment tried to put the number 42 into a List. The compiler refused, and its real message is:

Main.java:6: error: incompatible types: int cannot be converted to String
        names.add(42);

Without generics, this mistake would only show up later, when some other part of the program takes an item out of the list, expects a String and finds an Integer. A compile error at the mistake itself is far cheaper than a crash in production.

Check by hand: 3 days x 1200 = 3600. The ordinal counts from zero, FREE is 0, RENTED is 1 and REPAIR is 2, so RENTED is 1. Among “trail”, “city” and “tandem” the biggest in dictionary order is “trail”, because t-r comes after t-a and after c.

Records are shallowly immutable

The fields cannot be reassigned, but a record that holds a mutable list still lets the list change. Copy lists into immutable ones with List.copyOf.

Replace string constants with enums

If a field can take only a few values, such as a status or a size, make it an enum, and let the compiler find every place that needs updating.

About this course

Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21. Records need Java 16 or later.

Practice

Make a record Customer(String name, String email) with a compact constructor that rejects an empty name. Add an enum for membership levels with a discount percentage field. Write a generic method that returns the smallest element of a list.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does a record generate for you?

  1. Only a constructor
  2. A database table
  3. A thread
  4. A constructor, accessors, equals, hashCode and toString

It is an immutable data carrier.

Why prefer an enum over strings for a status?

  1. It is shorter to type
  2. Strings are illegal
  3. The compiler checks every value
  4. Enums use less memory always

A typo in the code does not compile.

What do generics prevent?

  1. Using lists
  2. Writing methods
  3. Putting the wrong type into a container unnoticed
  4. Importing packages

The error appears at compile time.

What is the ordinal of an enum constant?

  1. Its length
  2. Its zero-based position
  3. Its price
  4. Its hash

RENTED was 1.

What does the compact constructor do in a record?

  1. Deletes the record
  2. Validates or adjusts the fields
  3. Prints it
  4. Sorts it

It runs before the fields are assigned.

Summary

  • Records declare immutable data classes in one line.
  • Enums model fixed sets of values and catch typos at compile time.
  • Generics make containers type-safe.
  • Compiler errors are cheaper than run-time crashes.

Next lesson

Lesson 12 covers exceptions: how Java reports and handles failures.

Questions

Can a record extend a class?

No. Records are implicitly final and extend java.lang.Record, but they can implement interfaces.

What is a type parameter?

A placeholder such as T for a type that is chosen when the generic class is used.

Can an enum have methods?

Yes. Each constant can even override a method, which is useful for behaviour that depends on the value.

Progress is saved in this browser.