Records Flashcards
Can records extend other records or classes?
No, only implement interfaces
Can record parameters be used in methods inside record?
Yes, normally
Can record parameters auto. generated methods be overridden?
Yes, methods that are auto. generated from parameters can be overriden:
public record Test(int rows, int cols, String name) {
public int cols() {
return 5;
}
}
How do we use records parameters?
After instantiation, we get parameters by calling parameter names as methods. eg. test.rows()
What can records contain?
Other variables, methods, classes, interfaces, enums, annotations etc.
What types of constructors does record have?
Long and short (compact)
How does compact constructor look like and what is it used for?
public Test {}
For simple checks of the passed input parameters. This constructor cannot change input parameters.
How does long constructor look like and what is it used for?
public Test(int a, int b) {
public Test(int a, int b) {
// do a check
this.a = a;
this.b = b;
}
}
Used to run checks and change input parameters.
When are record fields set?
After constructor finishes
How many compact constructors can record have?
Only one, and it cannot be overloaded
How is constructor overloading done?
We create a new constructor with different signature that canonical (long) constructor. On its first line, we must call that canonical constructor with this(). After it is called, record is immutable.
// Canonical constructor public Person(String name, int age) { if (age < 0) throw new IllegalArgumentException("Age cannot be negative"); this.name = name; this.age = age; // Record becomes immutable here, after this constructor completes } // Overloaded constructor public Person(String name) { this(name, 0); // Record is NOT immutable here // Record is immutable here, after the canonical constructor has been called and completed }