Sub topic 9
Adding Methods and Static Factories to Records
A record gives you a constructor, accessors, equals, hashCode, and toString for free. You can also add your own code to the record body. This chapter shows two kinds of code you can add: instance methods and static factory methods.
Instance Methods
An instance method is a method that works on one particular object. Inside a record, an instance method can read the record's components directly by name.
Here is a Point record with a method that measures the distance to another point:
record Point(int x, int y) {
double distanceTo(Point other) {
return Math.hypot(x - other.x, y - other.y);
}
}Inside the method, x and y are this point's values. other.x reads the other point's value. You can write other.x() instead. Both work inside the record.
Math.hypot(a, b) returns the square root of a*a + b*b. That is the straight-line distance.
Static Factory Methods
A static factory method is a static method that creates and returns an object. It is an alternative to calling new directly. Factories help in three ways:
- They have names, so
Point.origin()says more thannew Point(0, 0). - They can hide common starting values.
- They can convert other input, such as a string, into a record.
record Point(int x, int y) {
static Point origin() {
return new Point(0, 0);
}
static Point parse(String text) {
String[] parts = text.split(",");
return new Point(Integer.parseInt(parts[0].trim()),
Integer.parseInt(parts[1].trim()));
}
}A factory still calls the canonical constructor in the end. Any validation you put in a compact constructor still runs.
"With" Methods: Changing a Copy
Record fields are final, so you cannot change a point after you create it. Instead, you write a method that returns a new record with one value changed. People often call these "with" methods.
Point withX(int newX) {
return new Point(newX, y);
}The original point stays the same. You get a fresh copy back.
A Complete Example
Put it all together and run it:
record Point(int x, int y) {
static Point origin() {
return new Point(0, 0);
}
static Point parse(String text) {
String[] parts = text.split(",");
return new Point(Integer.parseInt(parts[0].trim()),
Integer.parseInt(parts[1].trim()));
}
double distanceTo(Point other) {
return Math.hypot(x - other.x, y - other.y);
}
Point withX(int newX) {
return new Point(newX, y);
}
}
public class Main {
public static void main(String[] args) {
Point start = Point.origin();
Point end = Point.parse("3, 4");
System.out.println(start.distanceTo(end)); // 5.0
Point moved = end.withX(10);
System.out.println(end); // Point[x=3, y=4]
System.out.println(moved); // Point[x=10, y=4]
}
}Overriding Generated Methods
You can also replace a generated method. For example, you can write your own toString:
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}The method must be public, because the generated version is public.
Summary
| You add | Keyword | Purpose |
|---|---|---|
| Instance method | none | Compute something from the components |
| Static factory | `static` | Create a record with a clear name |
| "With" method | none | Return a changed copy |
| Override | `@Override public` | Replace generated behavior |
Exercise
Add a static factory method square(int side) to record Rectangle(int width, int height) {} that returns a rectangle with equal width and height. Then add an instance method area() that returns the area.
Show answer
record Rectangle(int width, int height) { static Rectangle square(int side) { return new Rectangle(side, side); } int area() { return width * height; } } Calling Rectangle.square(4).area() returns 16.
Exercise
Why does withX return a new Point instead of changing the existing one?
Show answer
A record's fields are final and cannot be reassigned after construction. The method has to build and return a new Point with the changed value. The original stays the same.