Java Record Constructor and Final Field Assignment Issue
Posted: Tue Dec 03, 2024 6:25 am
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.
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.