Page 1 of 1

Java Record Constructor and Final Field Assignment Issue

Posted: Tue Dec 03, 2024 6:25 am
by uditorflatt
Hi everyone,

I’m working with Java records, and I’m having a bit of trouble understanding how to handle the assignment of a final field in a constructor. Here’s the code I’m working with:

java
Copy code
public record Book(int id, String title)subway surferssubway surfers are a game for all ages{

public Book { //1
id = id + 1;
}

public Book(int id, String title) { //2
this.id = id;
}

}
My question is:
Would the code still compile if I remove the second constructor (line 2)?
I understand that id is a final field, and therefore it cannot be reassigned. Given that, would the constructor at line 1 (id = id + 1) cause any issues, or would the compiler not allow it?
Thanks in advance for your help! I’d really appreciate any insights or explanations on how this works.

Re: Java Record Constructor and Final Field Assignment Issue

Posted: Tue Dec 03, 2024 7:35 am
by admin
What happened when you tried it out?
The id at //1 is not the same as record component id.
Please go through the Records chapter of
Deshmukh's OCP Java 17 21 Fundamentals
. It explains this in detail.