Record Classes for Data Carriers
Demonstrates Java record classes as concise immutable data carriers with automatic constructors, accessors, equals, hashCode, and toString methods.
Code
import java.util.List;
import java.util.Objects;
public class RecordClasses {
public record Point(int x, int y) {
public Point {
if (x < 0 || y < 0) {
throw new IllegalArgumentException(
"Coordinates must be non-negative");
}
}
public double distanceTo(Point other) {
return Math.sqrt(
Math.pow(x - other.x, 2) +
Math.pow(y - other.y, 2)
);
}
}
public record Rectangle(Point topLeft, Point bottomRight) {
public int width() {
return bottomRight.x() - topLeft.x();
}
public int height() {
return bottomRight.y() - topLeft.y();
}
public int area() {
return width() * height();
}
}
public record Employee(
String name,
String department,
double salary,
List<String> skills
) {
public Employee {
Objects.requireNonNull(name);
skills = List.copyOf(skills);
}
}
public static void main(String[] args) {
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);
System.out.println("Distance: " + p1.distanceTo(p2));
Rectangle rect = new Rectangle(p1, p2);
System.out.println("Area: " + rect.area());
Employee emp = new Employee("Alice", "Engineering", 95000,
List.of("Java", "Python", "SQL"));
System.out.println(emp);
}
}Inside the snippet
The snippet is organized around the classes RecordClasses, Point, Rectangle and Employee and the functions Point, distanceTo, Rectangle and width.
IllegalArgumentException is the guard’s signal — thrown at the branch, before any partial work happens.
Putting it to use
The primary signature is public record Point(int x, int y)
The demo output is labeled (Distance:, Area:), so every printed line maps back to its originating operation.
main sequences Point, distanceTo, Rectangle and area; executing the file runs that flow once.
Core lines
return bottomRight.x() - topLeft.x();
return bottomRight.y() - topLeft.y();
return width() * height();
Interactive Tools for This Topic
FAQ
- Does the code validate its input?
- The code throws `IllegalArgumentException`. Handle it at the call site or let it propagate deliberately.
- What does Record Classes for Data Carriers print when run?
- Run it as a complete program — the output lines carry labels such as `Distance:`, `Area:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.