Sub topic 12
Record, Enum, or Class?
You now know three ways to make your own type in Java: enums, records, and regular classes. Each one fits a different job. Pick the right one and your code stays short and safe. Pick the wrong one and you fight the language.
This chapter gives you a simple way to choose. You will see clear rules, a worked example that uses all three types together, and the most common mistakes beginners make.
The Three Jobs
Each kind of type answers a different question.
- An enum is a type with a fixed list of values that you know when you write the code. Days of the week, card suits and traffic light colors all fit this.
- A record is a type that only carries data. Its values are set once, when you create it. Two records with the same data count as equal.
- A regular class is a type that can do anything. It can change over time, hide its inner details and extend another class.
The record and enum are both special cases. Java gives them a lot of free features because it knows exactly what they are for. The regular class gets fewer free features but has no limits.
Two words you need
State is the data an object holds at a given moment. For example, a shopping cart's state is the list of items inside it.
Mutable means the state can change after the object is created. Immutable means it cannot. A cart is mutable, because you add items to it. A point at (1, 2) should be immutable, because if it changed it would be a different point.
The Decision Rules
Ask these questions in order. Stop at the first clear answer.
- Is there a fixed set of possible values, and do you know all of them now? If yes, use an enum.
- Is it plain data that should never change after it is created? If yes, a record is likely the right pick.
- Does it need to extend another class, store extra hidden fields, or change over time? If yes, use a regular class.
A Side-by-Side Comparison
The table below shows what each kind of type can and cannot do.
| Question | Enum | Record | Regular class |
|---|---|---|---|
| Can you create new values with `new`? | No | Yes | Yes |
| Is the number of values fixed? | Yes | No | No |
| Can its fields change after creation? | Possible, but a bad idea | No (fields are final) | Yes |
| Free `equals`, `hashCode`, `toString`? | Yes | Yes, based on the data | No, you write them |
| Can it extend another class? | No | No | Yes |
| Can it implement interfaces? | Yes | Yes | Yes |
| Can it have extra instance fields? | Yes | No, only its components | Yes |
| Works in an exhaustive `switch`? | Yes | Yes, when sealed (later chapter) | Only when sealed |
A component is one of the values listed in a record's header. In record Point(int x, int y), the components are x and y.
Worked Example: A Pizza Shop
A small pizza shop program needs three things:
- A pizza size. There are only three sizes, and the shop knows them all. That is a fixed set, so it is an enum.
- An order line, such as "2 large Margheritas". It is just data: an item name, a size and a quantity. Once written down, it should not change. That makes it a record.
- A shopping cart. The customer adds lines to it over time, so it changes. That calls for a regular class.
Save this as Main.java and run it with java Main.java on JDK 17 or later.
import java.util.ArrayList;
import java.util.List;
enum Size {
SMALL(800), MEDIUM(1100), LARGE(1400);
private final int priceCents;
Size(int priceCents) {
this.priceCents = priceCents;
}
int priceCents() {
return priceCents;
}
}
record OrderLine(String item, Size size, int quantity) {
OrderLine {
if (quantity < 1) {
throw new IllegalArgumentException("quantity must be at least 1");
}
}
int totalCents() {
return size.priceCents() * quantity;
}
}
class ShoppingCart {
private final List<OrderLine> lines = new ArrayList<>();
void add(OrderLine line) {
lines.add(line);
}
int lineCount() {
return lines.size();
}
int totalCents() {
int sum = 0;
for (OrderLine line : lines) {
sum += line.totalCents();
}
return sum;
}
}
public class Main {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.add(new OrderLine("Margherita", Size.LARGE, 2));
cart.add(new OrderLine("Pepperoni", Size.SMALL, 1));
System.out.println("Lines: " + cart.lineCount());
System.out.println("Total: " + cart.totalCents() + " cents");
OrderLine a = new OrderLine("Pepperoni", Size.SMALL, 1);
OrderLine b = new OrderLine("Pepperoni", Size.SMALL, 1);
System.out.println("Same order? " + a.equals(b));
}
}The output is:
Lines: 2
Total: 3600 cents
Same order? trueWhy each choice fits
Sizeis an enum because nobody should be able to invent a size calledGIANTat run time. The compiler only accepts the three listed sizes. Each size also carries its price, so the size and its price are kept together.OrderLineis a record because it is pure data. Java writes the constructor, the accessorsitem(),size()andquantity(), andequals. That is whya.equals(b)istrue: the two lines hold the same data. The compact constructor rejects bad quantities.ShoppingCartis a class because its state changes every time you calladd. Its list is also private. The outside world sees onlyadd,lineCountandtotalCents, never the list itself. A record would expose its list through an accessor, which is not what we want here.
When a Regular Class Is the Better Choice
Records are so short that beginners want to use them everywhere. Use a regular class instead in these cases.
The object changes over time
A counter, a bank account balance or a game character's health all change. A record's fields are final, so you would have to create a new record for every change. A class is clearer here.
class Counter {
private int count;
void increment() {
count++;
}
int count() {
return count;
}
}Identity matters more than data
Identity means "which object is this?" as opposed to "what data does it hold?" Two customers might share the same name and birthday but still be two different people. A record would call them equal. A class uses identity for equals by default, which keeps two people with the same data separate.
You need hidden or extra fields
A record can only store its components. If you want a private cache, a running total or a field the caller never sees, you need a class.
You need to extend another class
Records and enums cannot use extends. If your type must inherit from an existing class, only a regular class can do it.
When an Enum Is the Better Choice
Choose an enum over a record or class when:
- The list of values is closed. Order statuses like
PLACED,COOKINGandDELIVEREDare a good example. - You want the compiler to catch typos.
Status.DELIVERDdoes not compile, but the string"deliverd"does. - You want an exhaustive
switch, where the compiler checks that every value is handled.
Do not use an enum when users or data files can add new values. Customer names, product names from a database and city names are all open sets. A record or class fits those better.
Common Mistakes and Edge Cases
| Mistake | What goes wrong | Better choice |
|---|---|---|
| Using an enum for an open set, like product names | You must change and recompile the code for every new product | Record or class |
| Using a record for something that changes, like a score | Every change creates a new object and the code gets awkward | Class |
| Using a class for plain data | You write `equals`, `hashCode` and `toString` by hand and may get them wrong | Record |
| Putting a setter-style field in an enum | All code shares that one constant, so a change affects everyone | Keep enum fields `final` |
| Using a record when two equal-looking objects must stay different | `equals` says they are the same | Class |
One edge case surprises many beginners. An enum can have a field that is not final, and Java allows it. But each enum constant exists only once in the whole program. If one part of your code changes Size.LARGE's field, every other part sees the change. Keep enum fields final and treat enum constants as fixed facts.
Another edge case: a record can hold a mutable object, such as an ArrayList. The record's field cannot point to a different list, but the list itself can still change. The earlier chapter on shallow immutability shows how a defensive copy fixes this.
A Quick Checklist
Before you write a new type, say its job out loud:
- "It is one of these few known things." Use an enum.
- "It is a bundle of values, and equal values mean equal objects." Use a record.
- "It is a thing that changes, hides its insides, or extends another class." Use a class.
If you are unsure between a record and a class, start with a record. The compiler will tell you quickly if you need something a record cannot do, such as an extra field or extends.
Exercise
A music app has (a) the genre of a song, chosen from a fixed list the app defines, (b) a song with a title, artist and length in seconds that never changes, and (c) a playlist that users add and remove songs from. Which kind of type fits each one?
Show answer
(a) Genre is an enum, because the list is fixed and known when the code is written. (b) Song is a record, because it is plain data that does not change and two songs with the same data can be treated as equal. (c) Playlist is a regular class, because its contents change over time and it should keep its list private.
Exercise
A teammate writes record Player(String name, int health) and then wants to lower a player's health when they get hit. Why is this awkward, and what would you suggest?
Show answer
Record fields are final, so health cannot be lowered in place. Every hit would need a brand-new Player record. Because the player's state changes often, a regular class with a private health field and a method such as takeDamage(int amount) fits better.
Exercise
Why is an enum safer than using static final String SMALL = "small"; for pizza sizes?
Show answer
With strings, any text can be passed where a size is expected, including typos like "smal", and the compiler cannot catch it. With an enum, only the declared constants exist, so invalid sizes do not compile. Switches over the enum can also be checked for exhaustiveness.