Record — immutable data carrier. Class — general-purpose object.
Record:
name() not getName()).Complete Record example:
1public record Point(int x, int y) {}23// Compact canonical constructor4public record Point(int x, int y) {5 public Point {6 if (x < 0 || y < 0) throw new IllegalArgumentException();7 }8}910// Usage11Point p = new Point(3, 4);12System.out.println(p); // Point[x=3, y=4]13System.out.println(p.x()); // 314System.out.println(p.y()); // 4
Class:
Complete Class example:
1public class Person {2 private final String name;3 private int age; // mutable45 public Person(String name, int age) {6 this.name = name;7 this.age = age;8 }910 public String getName() { return name; }11 public int getAge() { return age; }12 public void setAge(int age) { this.age = age; }1314 @Override15 public boolean equals(Object o) {16 if (this == o) return true;17 if (o == null || getClass() != o.getClass()) return false;18 Person person = (Person) o;19 return age == person.age && Objects.equals(name, person.name);20 }2122 @Override23 public int hashCode() {24 return Objects.hash(name, age);25 }26}
When to use Record:
When to use Class: