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);
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.