Records, enums and sealed classes
Three modern tools that remove boilerplate and make models safer. Records for data, enums for fixed sets of values, sealed classes for closed hierarchies.
Modern Java has three special kinds of class that make everyday models shorter and safer. You'll see them all over modern codebases and in interviews about "what's new in Java".
01Records: data classes in one line (Java 16+)
Many classes just carry data: a DTO, an API response, a pair of values. Writing the constructor, getters, equals, hashCode and toString by hand is long and easy to get wrong. A record generates all of it:
record Money(long paise, String currency) {
Money { // compact constructor: validation
if (paise < 0) throw new IllegalArgumentException("Negative amount");
}
Money add(Money other) { // records can have methods
return new Money(paise + other.paise, currency);
}
}
public class RecordDemo {
public static void main(String[] args) {
Money a = new Money(49900, "INR");
Money b = new Money(49900, "INR");
System.out.println(a); // generated toString
System.out.println(a.paise()); // accessor: paise(), not getPaise()
System.out.println(a.equals(b)); // generated equals
System.out.println(a.add(b));
}
}Money[paise=49900, currency=INR] 49900 true Money[paise=99800, currency=INR]
Records are immutable: fields are private final and there are no setters. A record can't extend another class (it implicitly extends java.lang.Record), but it can implement interfaces.
Loading the rest of the lesson…