Java language

Record alternate constructor

A noncanonical constructor must delegate to another constructor in the record. Centralize validation in the canonical constructor.

Formal Syntax & Structure

java syntaxjava
Ticket(int seats) { this(seats, 12); }

Working Example

Example Snippetjava
public class Main {    interface Costed { int cost(); }    record Ticket(int seats, int unitCost) implements Costed {        Ticket {            if (seats < 1 || seats > 100 || unitCost < 0 || unitCost > 1000) {                throw new IllegalArgumentException("Invalid ticket");            }        }        Ticket(int seats) { this(seats, 12); }        public int cost() { return seats * unitCost; }    }    public static void main(String[] args) {        Costed ticket = new Ticket(3);        System.out.println(ticket.cost());        System.out.println(new Ticket(3).equals(new Ticket(3, 12)));    }}
Java Reference