Page 1 of 1

About Question enthuware.ocpjp.v17.2.3694 :

Posted: Thu Oct 10, 2024 6:15 pm
by fgomezt
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).

Re: About Question enthuware.ocpjp.v17.2.3694 :

Posted: Thu Oct 10, 2024 8:13 pm
by admin
Please post in English only.

Re: About Question enthuware.ocpjp.v17.2.3694 :

Posted: Wed Dec 04, 2024 4:37 am
by rlobato
fgomezt wrote:
Thu Oct 10, 2024 6:15 pm
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).
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.

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

Re: About Question enthuware.ocpjp.v17.2.3694 :

Posted: Wed Dec 04, 2024 8:29 pm
by admin
Right, but I am not sure what your question is.