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.
Java Record Constructor and Final Field Assignment Issue
Moderator: admin
-
- Posts: 1
- Joined: Tue Dec 03, 2024 6:16 am
- Contact:
-
- Site Admin
- Posts: 10326
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: Java Record Constructor and Final Field Assignment Issue
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.
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.
If you like our products and services, please help us by posting your review here.
Who is online
Users browsing this forum: No registered users and 10 guests