por que, esta alternativa It will compile if the second constructor is removed altogether. sera la correcta si no se puede, modificar el argumento de entrada por ser final??? id = id+1;
Given: public record Journal(int id, String name){
public Journal{ //1 id = id+1; }
public Journal(int id, String name){ //2 this.id = id; }
}
Identify correct statement(s).
About Question enthuware.ocpjp.v17.2.3694 :
Moderator: admin
-
- Posts: 3
- Joined: Wed Apr 17, 2024 7:22 pm
- Contact:
-
- Site Admin
- Posts: 10269
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3694 :
Please post in English only.
If you like our products and services, please help us by posting your review here.
-
- Posts: 10
- Joined: Fri Jun 28, 2024 3:08 am
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3694 :
En un registro, los campos son finales, por lo que no puedes asignarles valores explícitamente en un constructor compacto (this.id = ... no está permitido). Sin embargo, puedes modificar los argumentos del constructor (por ejemplo, id = id + 1), y el compilador asigna automáticamente el argumento modificado a los campos finales al final del constructor compacto.fgomezt wrote: ↑Thu Oct 10, 2024 6:15 pmpor que, esta alternativa It will compile if the second constructor is removed altogether. sera la correcta si no se puede, modificar el argumento de entrada por ser final??? id = id+1;
Given: public record Journal(int id, String name){
public Journal{ //1 id = id+1; }
public Journal(int id, String name){ //2 this.id = id; }
}
Identify correct statement(s).
English:
In a record, the fields are final, so you cannot explicitly assign values to them in a compact constructor (this.id = ... is not allowed). However, you can modify the constructor arguments (e.g., id = id + 1), and the compiler automatically assigns the modified argument to the final fields at the end of the compact constructor.
For example:
Code: Select all
record MyRecord(int id) {
MyRecord {
id = id + 1; // Modify argument
// Compiler assigns: this.id = id
}
}
System.out.println(new MyRecord(10).id()); // Output: 11
-
- Site Admin
- Posts: 10269
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3694 :
Right, but I am not sure what your question is.
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 9 guests