Records in Java: Immutability, Conciseness, and Beyond

Records in Java are special classes, not subclasses of the regular class keyword. While they share some similarities with traditional classes, there are also key differences, especially regarding immutability and methods.

1. Immutability: Records are immutable by default. This means their state cannot be changed after creation. Once a record is created, its fields remain constant.

2. No Setters: Due to immutability, records don’t have setters. You cannot directly modify the values of their fields after the object is created.

3. Getters: Records automatically generate getters for all their fields. These methods allow you to access the current values of the fields.

4. Additional Methods: You can define your own custom methods within a record, just like in a regular class.

public record Person(String name, int age) {

  // Custom method to return a greeting message
  public String greet() {
    return "Hello, my name is " + name + " and I am " + age + " years old.";
  }
}

public class Main {

  public static void main(String[] args) {
    Person p1 = new Person("Alice", 30);

    // Accessing fields using getters (automatically generated)
    System.out.println("Name: " + p1.name());
    System.out.println("Age: " + p1.age());

    // Trying to modify a field directly (will not work)
    // p1.name = "Bob"; // Error: name cannot be assigned

    // Custom method usage
    System.out.println(p1.greet());
  }
}

In this example:

  • The Person record defines two fields: name (String) and age (int).
  • Getters are automatically generated for both fields, allowing access using p1.name() and p1.age().
  • Trying to modify the name field directly (p1.name = "Bob") results in an error due to immutability.
  • The greet() method is a custom method defined within the record.

Remember, records are a specific type of class with a focus on immutability and data encapsulation. While they lack traditional setter methods, they offer a clean and concise way to define data objects with guaranteed immutability.

You may also like...