Records Flashcards

1
Q

Can records extend other records or classes?

A

No, only implement interfaces

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Can record parameters be used in methods inside record?

A

Yes, normally

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Can record parameters auto. generated methods be overridden?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do we use records parameters?

A

After instantiation, we get parameters by calling parameter names as methods. eg. test.rows()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What can records contain?

A

Other variables, methods, classes, interfaces, enums, annotations etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What types of constructors does record have?

A

Long and short (compact)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How does compact constructor look like and what is it used for?

A

public Test {}

For simple checks of the passed input parameters. This constructor cannot change input parameters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How does long constructor look like and what is it used for?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

When are record fields set?

A

After constructor finishes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How many compact constructors can record have?

A

Only one, and it cannot be overloaded

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How is constructor overloading done?

A

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
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly