Java — Modeling values with records
A Java record declares its components together and supplies accessors for them. A line item can add a method that multiplies its quantity by its unit price.
A simple example
Read one field
- Start with A point with x = 2
- Do this Read x
- Result 2
class Main {
public static void main(String[] args) throws Exception {
record Point(int x) {}
var point = new Point(2);
System.out.println(point.x());
}
}
2
Represent an invoice line
A record declares its components and generates accessors, equality, and a constructor. The added method derives a subtotal whenever it is called. This example uses Java 17 or later.
A café invoice lists three juices at 125 cents each. Store the quantity and price together, then calculate the subtotal when the receipt is printed. Changing the quantity can then update the total automatically.
Run the example
Java 17 or later. Run these commands from the directory containing the example.
java Main.java
class Main {
record LineItem(int units, int cents) {
int subtotal() {
return units * cents;
}
}
public static void main(String[] args) {
LineItem line = new LineItem(3, 125);
System.out.println(line.subtotal());
}
}
375
The line holds three units at 125 cents each. Multiplication gives 375 cents. Keeping the subtotal derived means there is no third field that can become stale.
Try it yourself
Create a second line with two units at 90 cents each.
Check your answer
Its subtotal is 180 cents. The two subtotals together are 555 cents before any taxes or delivery charges.