compact constructor
A record constructor written without a parameter list, which runs checks before the record's fields are assigned.
In more detail
Because the component names are already declared in the record header, the compact constructor only contains validation or normalisation. Throwing an exception there, such as IllegalArgumentException, prevents an invalid record from ever existing. That is the place for invariants every instance must satisfy.
Example
public Customer { if (id.isBlank()) throw new IllegalArgumentException("customer fields are required"); }Related terms
- record (Java) — A compact Java class for plain data, declared with its components in one line, for which the compiler generates the fields, accessors, equals, hashCode and toString.
- invariant — A rule that must always hold for an object or system, such as a count never being negative.
- IllegalArgumentException — The standard unchecked exception for a method argument that is not acceptable, such as a blank identifier or a negative count.
Taught in
- Primitive And Reference Types — Modern Java: Virtual Threads & High-Throughput Services
- Records And Data Classes — Modern Java: Virtual Threads & High-Throughput Services
- Classes, Records And Initialisation Order — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Scope, var And Immutable Objects — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Sprint: Object-Oriented Java — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Serialization: What Survives The Trip — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Mock Exam: Sit It, Score It — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep