0Pricing
Java Academy · Lesson

Custom Methods on Records

Add instance methods and static factory methods to enrich record functionality.

Custom Methods on Records

Records can contain instance methods, static methods, and static fields — any behavior that derives from or relates to the record's components.

Instance Methods on Records

Add methods to records to compute derived values or provide useful operations based on the components.

record Money(long cents, String currency) {
    public double amount() { return cents / 100.0; }
    public String display() { return String.format("%s %.2f", currency, amount()); }
    public Money add(Money other) {
        if (!currency.equals(other.currency))
            throw new IllegalArgumentException("Currency mismatch");
        return new Money(cents + other.cents, currency);
    }
    public Money multiply(int factor) { return new Money(cents * factor, currency); }
}

Money price = new Money(1999, "USD");
Money tax = new Money(160, "USD");
System.out.println(price.add(tax).display()); // USD 21.59

All lessons in this course

  1. Introducing Records
  2. Compact Constructors and Validation
  3. Custom Methods on Records
  4. Records vs Classes vs Lombok
← Back to Java Academy