CoDemystified JavaFx CoDemystified JavaFx - 4 months ago 11
Java Question

Declaring final via constructor arg to set member variable vs declaring final via member variable and setting it via the constructor arg?

Class I have come across below: -

public class StackOverflow {

// Is this variable final?
private String question;

public StackOverflow (final String question) {
this.question = question;


How I would have written to enforce a final member: -

public class StackOverflow {

private final String question;

public StackOverflow (String question) {
this.question = question;


I think theres will not work as expected but I cannot rationalise why.

If I am wrong please explain why.

What is the technical difference between mine and theirs?

I am not asking what a final variable is. I am asking whether the constructor is setting the member to an unmodifiable variable in both case.

i.e. reference vs value

Please help.


Their code and yours are doing two completely different things.

Their code protects the constructor argument question from modification (i.e. reassignment) within the constructor

Your code protects the instance variable question from modification.