Sub topic 9
Adding Methods and Static Factories to Records
A record gives you a constructor, accessors, equals, hashCode, and toString for free. A record is still a class, though, so you can add your own code to it. This chapter shows the two kinds of code you will add most often: instance methods and static factory methods.
By the end of this chapter you will be able to:
- Add instance methods that compute answers from a record's components.
- Add static factory methods that build records in clear, named ways.
- Add "with" methods that return a changed copy of a record.
- Add static constants to a record.
Two Kinds of Methods
First, some terms.
- An instance method is a method that belongs to one object. You call it on a value, like
p.distanceTo(q). Inside it, you can use that object's components. - A static method is a method that belongs to the type itself, not to one object. You call it on the type name, like
Point.origin(). It has no "current object" to read from. - A static factory method is a static method whose job is to create and return a new object. It is an alternative to calling
newdirectly.
Records allow both kinds. You write them inside the record's curly braces, just as you would in a normal class.
Instance Methods: Answers Computed from Components
The components of a record are its stored data. Often you want answers that come from that data, such as a distance, a total, or a yes/no check. An instance method is the place for that.
Here is a Point record with a static factory and an instance method:
record Point(int x, int y) {
static Point origin() {
return new Point(0, 0);
}
double distanceTo(Point other) {
return Math.hypot(x - other.x, y - other.y);
}
}
public class Main {
public static void main(String[] args) {
Point start = Point.origin();
Point end = new Point(3, 4);
System.out.println(start); // Point[x=0, y=0]
System.out.println(start.distanceTo(end)); // 5.0
}
}Save this as Main.java, then run java Main.java with JDK 17 or later.
Look at the inside of distanceTo. It uses x and y with no prefix. Inside a record, the component names refer to the private fields the compiler created for you. It also reads other.x directly. That works because code inside the record may see the private fields of any Point, not only its own.
Math.hypot(a, b) is a standard Java method. It returns the square root of a*a + b*b, which is the straight-line distance.
Calling accessors versus fields
Inside the record you can write x or x(). Both give the same number here. Outside the record, other code must use the accessor p.x(), because the field is private. Many people use the plain field name inside the record because it is shorter. Either choice is fine. Pick one and use it the same way throughout.
Static Factory Methods: Named Ways to Build a Record
Every record has one canonical constructor, which is the constructor that takes all components in order. Sometimes that is not the most natural way to create a value. Static factories let you offer other ways, each with a name that says what it does.
Example: one value, two units
A temperature can be given in Celsius or Fahrenheit. A constructor cannot have two versions that both take a single double, because Java could not tell them apart. Two named factories solve this.
record Temperature(double celsius) {
static final Temperature FREEZING = new Temperature(0.0);
static Temperature ofCelsius(double c) {
return new Temperature(c);
}
static Temperature ofFahrenheit(double f) {
return new Temperature((f - 32) * 5 / 9);
}
double fahrenheit() {
return celsius * 9 / 5 + 32;
}
boolean isBelowFreezing() {
return celsius < FREEZING.celsius;
}
}
public class Main {
public static void main(String[] args) {
Temperature a = Temperature.ofCelsius(25);
Temperature b = Temperature.ofFahrenheit(212);
System.out.println(a.fahrenheit()); // 77.0
System.out.println(b.celsius()); // 100.0
System.out.println(b.isBelowFreezing()); // false
System.out.println(Temperature.FREEZING); // Temperature[celsius=0.0]
}
}Several things are happening here:
ofCelsiusandofFahrenheitare static factories. Both return aTemperature, and both end by calling the canonical constructor.FREEZINGis a static constant, astatic finalfield shared by the whole type. Records allow static fields. They do not allow extra instance fields, which is covered in the chapter "What Records Cannot Do."fahrenheit()is an instance method that converts on demand. The record stores only Celsius.
Common factory names
Java's own libraries use a few naming habits. Following them makes your code easier for others to read.
| Name | Meaning | Example from the JDK |
|---|---|---|
| `of` | Build from the given parts | `List.of(1, 2, 3)` |
| `from` | Convert from another type | `Instant.from(...)` |
| `parse` | Read from text | `Integer.parseInt("42")` |
| a descriptive noun | A well-known special value | `Point.origin()` |
Example: parsing text
A parse factory turns a string into a record. This is a good place to check the input, because the string might be badly formed.
record Point(int x, int y) {
static Point parse(String text) {
String[] parts = text.split(",");
if (parts.length != 2) {
throw new IllegalArgumentException("Expected \"x,y\" but got: " + text);
}
int x = Integer.parseInt(parts[0].trim());
int y = Integer.parseInt(parts[1].trim());
return new Point(x, y);
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Point.parse("3, 4")); // Point[x=3, y=4]
System.out.println(Point.parse(" -1,7 ")); // Point[x=-1, y=7]
}
}The factory splits the text at the comma, trims spaces, and turns each part into an int. If the text has the wrong shape, it throws an exception with a helpful message.
The diagram below shows how the paths fit together.
"With" Methods: Changing a Copy
Record components cannot be reassigned after the record is built. So how do you "move" a point? You make a new one. A with method is an instance method that returns a copy of the record with one component changed.
record Point(int x, int y) {
Point withX(int newX) {
return new Point(newX, y);
}
Point withY(int newY) {
return new Point(x, newY);
}
Point plus(Point other) {
return new Point(x + other.x, y + other.y);
}
}
public class Main {
public static void main(String[] args) {
Point p = new Point(1, 2);
Point moved = p.withX(10);
System.out.println(p); // Point[x=1, y=2]
System.out.println(moved); // Point[x=10, y=2]
System.out.println(p.plus(new Point(5, 5))); // Point[x=6, y=7]
}
}Notice that p is unchanged after withX. The method built a fresh Point. This is the normal style for records: methods that seem to "change" something return a new value instead.
Overriding Generated Methods
You may also write your own version of a method the record would generate. This is called overriding. A common case is a nicer toString:
record Point(int x, int y) {
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Point(3, 4)); // (3, 4)
}
}Follow these rules when you override:
toString,equals, andhashCodemust bepublic, as they are in every class.- If you override an accessor such as
x(), it must also bepublicand return the same type as the component. - Keep
equalsandhashCodeas generated unless you have a strong reason to change them. The generated versions compare all components, which is almost always what you want.
Summary
| You want to... | Add this | Example |
|---|---|---|
| Compute an answer from the data | Instance method | `distanceTo`, `fahrenheit` |
| Offer a named way to create values | Static factory | `origin`, `ofFahrenheit`, `parse` |
| Share one fixed value | Static constant | `Temperature.FREEZING` |
| "Change" one component | With method returning a new record | `withX` |
| Customize printing | Override `toString` | `(3, 4)` |
Exercise
Add a static factory square(int side) to record Rectangle(int width, int height) {} that returns a rectangle with equal width and height, and an instance method area() that returns width times height. What does Rectangle.square(4).area() return?
Show answer
Write static Rectangle square(int side) { return new Rectangle(side, side); } and int area() { return width * height; } inside the record's braces. Rectangle.square(4).area() returns 16.
Exercise
After running Point p = new Point(1, 2); p.withY(9); System.out.println(p);, what is printed, and why?
Show answer
It prints Point[x=1, y=2]. withY returns a new Point, but the result is never stored, and p still refers to the original, unchanged record. Write p = p.withY(9); to keep the new value.
Exercise
A Range(int start, int end) record has a factory Range.of(int a, int b) that throws if a > b. Why is it not enough to put this check only in the factory?
Show answer
Callers can skip the factory and call new Range(5, 1) directly, which would create an invalid range. A rule that must hold for every Range belongs in the compact constructor, because every creation path, including factories, runs through it.